home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / ld / dist / patch2 / RCS / ld.c,v < prev   
Encoding:
Text File  |  1990-10-30  |  175.3 KB  |  6,516 lines

  1. head     1.1;
  2. branch   ;
  3. access   ;
  4. symbols  ;
  5. locks    rab:1.1; strict;
  6. comment  @ * @;
  7.  
  8.  
  9. 1.1
  10. date     90.10.30.02.49.32;  author rab;  state Exp;
  11. branches ;
  12. next     ;
  13.  
  14.  
  15. desc
  16. @@
  17.  
  18.  
  19.  
  20. 1.1
  21. log
  22. @Initial revision
  23. @
  24. text
  25. @/* Linker `ld' for GNU
  26.    Copyright (C) 1988 Free Software Foundation, Inc.
  27.  
  28.    This program is free software; you can redistribute it and/or modify
  29.    it under the terms of the GNU General Public License as published by
  30.    the Free Software Foundation; either version 1, or (at your option)
  31.    any later version.
  32.  
  33.    This program is distributed in the hope that it will be useful,
  34.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  35.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  36.    GNU General Public License for more details.
  37.  
  38.    You should have received a copy of the GNU General Public License
  39.    along with this program; if not, write to the Free Software
  40.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  41.  
  42. /* Written by Richard Stallman with some help from Eric Albert.
  43.    Set, indirect, and warning symbol features added by Randy Smith.  */
  44.  
  45. #include <ar.h>
  46. #include <stdio.h>
  47. #include <sys/types.h>
  48. #include <sys/stat.h>
  49. #include <sys/file.h>
  50. #ifndef USG
  51. #include <sys/time.h>
  52. #include <sys/resource.h>
  53. #endif
  54. #ifndef sony_news
  55. #include <fcntl.h>
  56. #endif
  57.  
  58. #define TARGET_SUN2             2
  59. #define TARGET_SUN3             3
  60. #define TARGET_SUN4             4
  61. #define TARGET_ALTOS            5
  62. #define TARGET_I386             6   
  63. #define TARGET_HPUX             7
  64. #define TARGET_SONY_NEWS        8
  65. #define TARGET_SEQUENT          9
  66. #define TARGET_VAX              10
  67.  
  68. /*
  69.  * If `TARGET_MACHINE' was not defined on the compiler command line,
  70.  * then set it equal to the host machine.
  71.  */
  72. #ifndef TARGET_MACHINE
  73. #if defined(sun) && defined(sparc)
  74. #define TARGET_MACHINE  TARGET_SUN4
  75. #endif
  76. #if defined(sun) && (defined(m68020) || defined(mc68020))
  77. #define TARGET_MACHINE  TARGET_SUN3
  78. #endif
  79. #if defined(sun) && (defined(m68010) || defined(mc68010))
  80. #define TARGET_MACHINE  TARGET_SUN2
  81. #endif
  82. #if defined(ALTOS)
  83. #define TARGET_MACHINE  TARGET_ALTOS
  84. #endif
  85. #if defined(hpux)
  86. #define TARGET_MACHINE  TARGET_HPUX
  87. #endif
  88. #if defined(is386)
  89. #define TARGET_MACHINE  TARGET_I386
  90. #endif
  91. #if defined(sony_news)
  92. #define TARGET_MACHINE  TARGET_SONY_NEWS
  93. #endif
  94. #if defined(sequent)
  95. #define TARGET_MACHINE  TARGET_SEQUENT
  96. #endif
  97. #if defined(is68k) && !defined(TARGET_MACHINE)
  98. #define TARGET_MACHINE  TARGET_68K
  99. #endif
  100. #endif
  101.  
  102. #ifndef TARGET_MACHINE
  103.  CANNOT COMPILE, NO TARGET MACHINE SPECIFIED
  104. #endif
  105.  
  106. #ifndef BIG_ENDIAN
  107. #define BIG_ENDIAN      4321
  108. #endif
  109. #ifndef LITTLE_ENDIAN
  110. #define LITTLE_ENDIAN   1234
  111. #endif
  112. #ifndef PDP_ENDIAN
  113. /* I think it is unlikely that anybody will try to cross compile
  114.  * to or from a pdp, so only big-endian and little-endian are supported. */
  115. #define PDP_ENDIAN   3412
  116. #endif
  117.  
  118. #if TARGET_MACHINE==TARGET_SUN4      || \
  119.  TARGET_MACHINE==TARGET_SUN3         || \
  120.  TARGET_MACHINE==TARGET_SUN2         || \
  121.  TARGET_MACHINE==TARGET_ALTOS        || \
  122.  TARGET_MACHINE==TARGET_HPUX         || \
  123.  TARGET_MACHINE==TARGET_SONY_NEWS    || \
  124.  TARGET_MACHINE==TARGET_68K
  125. #define TARGET_BYTE_ORDER       BIG_ENDIAN
  126. #endif
  127.  
  128. #if TARGET_MACHINE==TARGET_VAX          || \
  129.  TARGET_MACHINE==TARGET_I386         || \
  130.  TARGET_MACHINE==TARGET_SEQUENT
  131. #define TARGET_BYTE_ORDER       LITTLE_ENDIAN
  132. #endif
  133.  
  134. #if TARGET_MACHINE==TARGET_SUN3
  135. #define TARGET_PAGE_SIZE    0x2000
  136. #endif
  137.  
  138. #if defined(sparc)   || \
  139.  defined(m68000)     || \
  140.  defined(mc68000)    || \
  141.  defined(m68010)     || \
  142.  defined(mc68010)    || \
  143.  defined(m68020)     || \
  144.  defined(mc68020)    || \
  145.  defined(is68k)      || \
  146.  defined(hpux)       || \
  147.  defined(sony_news)
  148. #define HOST_BYTE_ORDER     BIG_ENDIAN
  149. #endif
  150.  
  151. #if defined(vax)     || \
  152.  defined(is386)      || \
  153.  defined(ds3100)     || \
  154.  defined(sequent)
  155. #define HOST_BYTE_ORDER     LITTLE_ENDIAN
  156. #endif
  157.  
  158. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  159. static void fix_byte_order();
  160. static void fix_exec_header_byte_order();
  161. static void fix_symbol_byte_order();
  162. static void target_to_host_reloc_byte_order();
  163. static void host_to_target_reloc_byte_order();
  164. static void fix_symbol_root_byte_order();
  165. #endif
  166.  
  167. #if !defined(A_OUT) && !defined(MACH_O)
  168. #define A_OUT
  169. #endif
  170.  
  171. #ifdef A_OUT
  172. #ifdef COFF_ENCAPSULATE
  173. #include "a.out.encap.h"
  174. #else
  175. #ifdef sprite
  176. #if TARGET_MACHINE==TARGET_SUN4
  177. #include <sun4.md/a.out.h>
  178. #elif TARGET_MACHINE==TARGET_SUN3
  179. #include <sun3.md/a.out.h>
  180. #elif TARGET_MACHINE==TARGET_SEQUENT
  181. #include <symm.md/a.out.h>
  182. #else
  183.  no a.out.h specified
  184. #endif
  185. #else
  186. #include <a.out.h>
  187. #endif
  188. #endif
  189. #endif
  190.  
  191. #ifdef MACH_O
  192. #ifndef A_OUT
  193. #include <nlist.h>
  194. #include <reloc.h>
  195. #endif
  196. #ifndef N_TEXT
  197. #define N_TEXT 0x04
  198. #define N_DATA 0x06
  199. #define N_BSS 0x08
  200. #endif
  201. #include <sys/loader.h>
  202. #endif
  203.  
  204. #ifdef sprite
  205. #undef NEW_SEG_SIZE
  206. #if TARGET_MACHINE==TARGET_SUN4
  207. #define NEW_SEG_SIZE    0x40000
  208. #endif
  209. #if TARGET_MACHINE==TARGET_SUN3
  210. #define NEW_SEG_SIZE    0x20000
  211. #endif
  212. #endif  /* sprite */
  213.  
  214. #ifndef N_SET_MAGIC
  215. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  216. #endif
  217.  
  218. /* If compiled with GNU C, use the built-in alloca */
  219. #ifdef __GNUC__
  220. # define alloca __builtin_alloca
  221. #else
  222. # if defined(sun) && defined(sparc)
  223. #  include "alloca.h"
  224. # else
  225. char *alloca ();
  226. # endif
  227. #endif
  228.  
  229. #include "getopt.h"
  230.  
  231. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  232.  
  233. #include "stab.h"
  234. #define CORE_ADDR unsigned long    /* For symseg.h */
  235. #include "symseg.h"
  236.  
  237. #ifdef USG
  238. #include <string.h>
  239. #else
  240. #include <strings.h>
  241. #endif
  242.  
  243. /* Determine whether we should attempt to handle (minimally)
  244.    N_BINCL and N_EINCL.  */
  245.  
  246. #if defined (__GNU_STAB__) || defined (N_BINCL)
  247. #define HAVE_SUN_STABS
  248. #endif
  249.  
  250. #define min(a,b) ((a) < (b) ? (a) : (b))
  251.  
  252. /* Macro to control the number of undefined references printed */
  253. #define MAX_UREFS_PRINTED    10
  254.  
  255. /* Size of a page; obtained from the operating system.  */
  256.  
  257. int page_size;
  258.  
  259. /* Name this program was invoked by.  */
  260.  
  261. char *progname;
  262.  
  263. /* System dependencies */
  264.  
  265. /* Define this if names etext, edata and end should not start with `_'.  */
  266. /* #define nounderscore 1 */
  267.  
  268. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  269.    whose native format is different.  */
  270. /* #define NON_NATIVE */
  271.  
  272. /* Define this to specify the default executable format.  */
  273.  
  274. #if TARGET_MACHINE==TARGET_HPUX
  275. #define DEFAULT_OUTPUT_STYLE OUTPUT_READONLY_TEXT
  276. #endif
  277.  
  278. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  279.  
  280. #ifndef N_TXTADDR
  281. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  282. #define N_TXTADDR(X) 0
  283. #endif
  284. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  285. #define N_TXTADDR(x)  (sizeof (struct exec))
  286. #endif
  287. #if TARGET_MACHINE==TARGET_SEQUENT
  288. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  289. #endif
  290. #ifdef TARGET_MACHINE==TARGET_NeXT
  291. #define N_TXTADDR(X) ((X).a_magic == ZMAGIC ? page_size : 0)
  292. #endif
  293. #endif
  294.  
  295. #ifndef N_DATADDR
  296. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  297. #define N_DATADDR(x) \
  298.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  299.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  300. #endif
  301. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  302. #define SEGMENT_SIZE 0x20000
  303. #define N_DATADDR(x) \
  304.     (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  305.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  306. #endif
  307. #if TARGET_MACHINE==TARGET_SEQUENT
  308. #define N_DATADDR(x) \
  309.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  310.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  311. #endif
  312. #ifdef TARGET_MACHINE==TARGET_MACHINE_NeXT
  313. #define N_DATADDR(X) \
  314.     (((X).a_magic==ZMAGIC)?(N_TXTADDR(X)+(X).a_text+0xFFFF)&~0xFFFF \
  315.      :N_TXTADDR(X)+(X).a_text)
  316. #endif
  317. #endif
  318.  
  319. /* The "address" of the data segment in a relocatable file.
  320.    The text address of a relocatable file is always
  321.    considered to be zero (instead of the value of N_TXTADDR, which
  322.    is what the address is in an executable), so we need to subtract
  323.    N_TXTADDR from N_DATADDR to get the "address" for the input file.  */
  324. #define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
  325.  
  326. /* Define how to initialize system-dependent header fields.  */
  327. #if TARGET_MACHINE==TARGET_SUN4
  328. #define INITIALIZE_HEADER \
  329.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  330. #endif /* sparc.  */
  331. #if TARGET_MACHINE==TARGET_SUN2 || TARGET_MACHINE==TARGET_SUN3
  332. /* Set the machine type according to the machine type of the .o files.
  333.    If they are all sun2 (68010), then the type of the executable is sun2.
  334.    If any is sun3 (68020), then the type of the executable is sun3.
  335.    This is consistent with the Sun loader and more useful than having
  336.    it depend on which machine you are on when you run ld.  */
  337. static int sun_machtype = M_68010;
  338. #define INITIALIZE_HEADER outheader.a_machtype = sun_machtype
  339. #define READ_HEADER_HOOK(machtype) \
  340.   if (machtype == M_68020)           \
  341.     {                     \
  342.       sun_machtype = M_68020;         \
  343.     }
  344. #endif
  345.  
  346. #if TARGET_MACHINE==TARGET_ALTOS
  347. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  348. #endif
  349. #if TARGET_MACHINE==TARGET_68K
  350. #ifdef M_68020
  351. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  352.    a_machtype field and so won't recognize the magic number.  To keep
  353.    binary compatibility for now, just ignore it */
  354. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  355. #endif
  356. #endif
  357. #if TARGET_MACHINE==TARGET_HPUX
  358. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  359. #endif
  360. #if TARGET_MACHINE==TARGET_I386
  361. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  362. #endif
  363. #if TARGET_MACHINE==TARGET_HP300
  364. #define INITIALIZE_HEADER outheader.a_mid = MID_HP300
  365. #endif
  366. #if TARGET_MACHINE==TARGET_PYR
  367. #define INITIALIZE_HEADER outheader.a_machid = PYR90X
  368. #endif /* Pyramid.  */
  369.  
  370. #if TARGET_MACHINE==TARGET_68K
  371. /* This enables code to take care of an ugly hack in the ISI OS.
  372.    If a symbol beings with _$, then the object file is included only
  373.    if the rest of the symbol name has been referenced. */
  374. #define DOLLAR_KLUDGE
  375. #endif
  376. #if TARGET==TARGET_SEQUENT
  377. /* This is all stuff needed to make standalone binaries */
  378. static struct gdtbl gdt_filler = {
  379.     { 0x0000FFFF, 0x00CF9A00 },    /* code entry */
  380.     { 0x0000FFFF, 0x00CF9200 },    /* data entry */
  381.     { 0x00180017, 0x00000000 },    /* 6 byte descriptor */
  382. };
  383.  
  384. static char instr[] = {
  385.     0x67, 0x66, 0x0f, 0x01, 0x15, 0x30, 0x00, 0x00, 0x00,
  386.     0x0f, 0x20, 0xc3,
  387.     0x80, 0xcb, 0x01,
  388.     0x0f, 0x22, 0xc3,
  389.     0xea, 0x5b, 0x00, 0x08, 0x00,
  390.     0xbb, 0x10, 0x00, 0x00, 0x00,
  391.     0x8e, 0xdb,
  392.     0x8e, 0xd3,
  393.     0x8e, 0xc3,
  394.     0xff, 0x25, 0x6c, 0x00, 0x00, 0x00,
  395.     0x00, 0x00, 0x00, 0x00, };
  396. #endif   
  397.  
  398. /* Values for 3rd argument to lseek().  */
  399. #ifndef L_SET
  400. #define L_SET 0
  401. #endif
  402. /* This is called L_INCR in BSD, but SEEK_CUR in POSIX.  */
  403. #ifndef SEEK_CUR
  404. #define SEEK_CUR 1
  405. #endif
  406.  
  407. /*
  408.  * Ok.  Following are the relocation information macros.  If your
  409.  * system cannot use the default set (below), you must define all of these:
  410.  
  411.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  412.  * of structure that is stored in the relocation info section of your
  413.  * a.out files.  Often this is defined in the a.out.h for your system.
  414.  *
  415.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  416.  * <whatever> to be relocated.  *Must be an lvalue*.
  417.  *
  418.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  419.  * external symbol (1), or was it fully resolved upon entering the
  420.  * loader (0) in which case some combination of the value in memory
  421.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  422.  * what the value of the relocation actually was.  *Must be an lvalue*.
  423.  *
  424.  *   RELOC_TYPE (rval): For a non-external relocation, this is the
  425.  * segment to relocate for.  *Must be an lvalue.*
  426.  *
  427.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  428.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  429.  *
  430.  *   RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
  431.  * relocation value output here should be added to memory; 0, if the
  432.  * section of memory described should simply be set to the relocation
  433.  * value.
  434.  *
  435.  *   RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
  436.  * present in the memory location to be relocated is *added*
  437.  * to the relocation value, to produce the final result.
  438.  * Otherwise, the relocation value is stored in the memory location
  439.  * and the value previously found there is ignored.
  440.  * By default, this is always 1.
  441.  *
  442.  *   RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
  443.  * present in the memory location to be relocated is *subtracted*
  444.  * from the relocation value, to produce the final result.
  445.  * By default, this is always 0.
  446.  *
  447.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  448.  * an extra value to be added to the relocation value based on the
  449.  * individual relocation entry.  *Must be an lvalue if defined*.
  450.  *
  451.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  452.  * pc relative.
  453.  *
  454.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  455.  * final relocation value before putting it where it belongs.
  456.  *
  457.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  458.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  459.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  460.  * do everything in terms of the bit operators below), but having this
  461.  * macro could end up producing better code on machines without fancy
  462.  * bit twiddling.  Also, it's easier to understand/code big/little
  463.  * endian distinctions with this macro.
  464.  *
  465.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  466.  * object described in RELOC_TARGET_SIZE in which the relocation value
  467.  * will go.
  468.  *
  469.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  470.  * with the bits of the relocation value.  It may be assumed by the
  471.  * code that the relocation value will fit into this many bits.  This
  472.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  473.  *
  474.  *
  475.  *        Things I haven't implemented
  476.  *        ----------------------------
  477.  *
  478.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  479.  *
  480.  *    Pc relative relocation for External references.
  481.  *
  482.  *
  483.  */
  484.  
  485. #if TARGET_MACHINE==TARGET_SUN4
  486. /* Sparc (Sun 4) macros */
  487. #undef relocation_info
  488. #define relocation_info                    reloc_info_sparc
  489. #define RELOC_ADDRESS(r)        ((r)->r_address)
  490. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  491. #define RELOC_TYPE(r)                   ((r)->r_index)
  492. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  493. #define RELOC_MEMORY_SUB_P(r)        0
  494. #define RELOC_MEMORY_ADD_P(r)           0
  495. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  496. #define RELOC_PCREL_P(r)                \
  497.  ((int) (r)->r_type >= (int) RELOC_DISP8 && \
  498.   (int) (r)->r_type <= (int) RELOC_WDISP22)
  499. #define RELOC_VALUE_RIGHTSHIFT(r) \
  500.     (reloc_target_rightshift[(int) (r)->r_type])
  501. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(int) (r)->r_type])
  502. #define RELOC_TARGET_BITPOS(r)          0
  503. #define RELOC_TARGET_BITSIZE(r) \
  504.     (reloc_target_bitsize[(int) (r)->r_type])
  505.  
  506. /* Note that these are very dependent on the order of the enums in
  507.    enum reloc_type (in a.out.h); if they change the following must be
  508.    changed */
  509. /* Also note that the last few may be incorrect; I have no information */
  510. static int reloc_target_rightshift[] = {
  511.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  512. };
  513. static int reloc_target_size[] = {
  514.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  515. };
  516. static int reloc_target_bitsize[] = {
  517.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  518. };
  519.  
  520. #define    MAX_ALIGNMENT    (sizeof (double))
  521.   /* The pagesize on an old sun4 is 0x2000, on sparcStation it is 0x1000.
  522.      If you want to use the same binaries on both, then you need to use
  523.      the larger pagesize. */
  524. #define TARGET_PAGE_SIZE    0x2000
  525. #endif
  526.  
  527. #if TARGET_MACHINE==TARGET_SEQUENT
  528. #define RELOC_ADDRESS(r)        ((r)->r_address)
  529. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  530. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  531. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  532. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  533. #define RELOC_MEMORY_ADD_P(r)    1
  534. #undef RELOC_ADD_EXTRA
  535. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  536. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  537. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  538. #define RELOC_TARGET_BITPOS(r)    0
  539. #define RELOC_TARGET_BITSIZE(r)    32
  540. #define TARGET_PAGE_SIZE    0x1000
  541. #endif
  542.  
  543. /* Default macros */
  544. #ifndef RELOC_ADDRESS
  545. #define RELOC_ADDRESS(r)        ((r)->r_address)
  546. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  547. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  548. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  549. #define RELOC_MEMORY_SUB_P(r)    0
  550. #define RELOC_MEMORY_ADD_P(r)    1
  551. #undef RELOC_ADD_EXTRA
  552. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  553. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  554. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  555. #define RELOC_TARGET_BITPOS(r)    0
  556. #define RELOC_TARGET_BITSIZE(r)    32
  557. #endif
  558.  
  559. #ifndef MAX_ALIGNMENT
  560. #define    MAX_ALIGNMENT    (sizeof (int))
  561. #endif
  562.  
  563. #ifdef nounderscore
  564. #define LPREFIX '.'
  565. #else
  566. #define LPREFIX 'L'
  567. #endif
  568.  
  569.  
  570. /* Special global symbol types understood by GNU LD.  */
  571.  
  572. /* The following type indicates the definition of a symbol as being
  573.    an indirect reference to another symbol.  The other symbol
  574.    appears as an undefined reference, immediately following this symbol.
  575.  
  576.    Indirection is asymmetrical.  The other symbol's value will be used
  577.    to satisfy requests for the indirect symbol, but not vice versa.
  578.    If the other symbol does not have a definition, libraries will
  579.    be searched to find a definition.
  580.  
  581.    So, for example, the following two lines placed in an assembler
  582.    input file would result in an object file which would direct gnu ld
  583.    to resolve all references to symbol "foo" as references to symbol
  584.    "bar".
  585.  
  586.     .stabs "_foo",11,0,0,0
  587.     .stabs "_bar",1,0,0,0
  588.  
  589.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  590.  
  591. #ifndef N_INDR
  592. #define N_INDR 0xa
  593. #endif
  594.  
  595. /* The following symbols refer to set elements.  These are expected
  596.    only in input to the loader; they should not appear in loader
  597.    output (unless relocatable output is requested).  To be recognized
  598.    by the loader, the input symbols must have their N_EXT bit set.
  599.    All the N_SET[ATDB] symbols with the same name form one set.  The
  600.    loader collects all of these elements at load time and outputs a
  601.    vector for each name.
  602.    Space (an array of 32 bit words) is allocated for the set in the
  603.    data section, and the n_value field of each set element value is
  604.    stored into one word of the array.
  605.    The first word of the array is the length of the set (number of
  606.    elements).  The last word of the vector is set to zero for possible
  607.    use by incremental loaders.  The array is ordered by the linkage
  608.    order; the first symbols which the linker encounters will be first
  609.    in the array.
  610.  
  611.    In C syntax this looks like:
  612.  
  613.     struct set_vector {
  614.       unsigned int length;
  615.       unsigned int vector[length];
  616.       unsigned int always_zero;
  617.     };
  618.  
  619.    Before being placed into the array, each element is relocated
  620.    according to its type.  This allows the loader to create an array
  621.    of pointers to objects automatically.  N_SETA type symbols will not
  622.    be relocated.
  623.  
  624.    The address of the set is made into an N_SETV symbol
  625.    whose name is the same as the name of the set.
  626.    This symbol acts like a N_DATA global symbol
  627.    in that it can satisfy undefined external references.
  628.  
  629.    For the purposes of determining whether or not to load in a library
  630.    file, set element definitions are not considered "real
  631.    definitions"; they will not cause the loading of a library
  632.    member.
  633.  
  634.    If relocatable output is requested, none of this processing is
  635.    done.  The symbols are simply relocated and passed through to the
  636.    output file.
  637.  
  638.    So, for example, the following three lines of assembler code
  639.    (whether in one file or scattered between several different ones)
  640.    will produce a three element vector (total length is five words;
  641.    see above), referenced by the symbol "_xyzzy", which will have the
  642.    addresses of the routines _init1, _init2, and _init3.
  643.  
  644.    *NOTE*: If symbolic addresses are used in the n_value field of the
  645.    defining .stabs, those symbols must be defined in the same file as
  646.    that containing the .stabs.
  647.  
  648.     .stabs "_xyzzy",23,0,0,_init1
  649.     .stabs "_xyzzy",23,0,0,_init2
  650.     .stabs "_xyzzy",23,0,0,_init3
  651.  
  652.    Note that (23 == (N_SETT | N_EXT)).  */
  653.  
  654. #ifndef N_SETA
  655. #define    N_SETA    0x14        /* Absolute set element symbol */
  656. #endif                /* This is input to LD, in a .o file.  */
  657.  
  658. #ifndef N_SETT
  659. #define    N_SETT    0x16        /* Text set element symbol */
  660. #endif                /* This is input to LD, in a .o file.  */
  661.  
  662. #ifndef N_SETD
  663. #define    N_SETD    0x18        /* Data set element symbol */
  664. #endif                /* This is input to LD, in a .o file.  */
  665.  
  666. #ifndef N_SETB
  667. #define    N_SETB    0x1A        /* Bss set element symbol */
  668. #endif                /* This is input to LD, in a .o file.  */
  669.  
  670. /* Macros dealing with the set element symbols defined in a.out.h */
  671. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  672. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  673.  
  674. #ifndef N_SETV
  675. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  676. #endif                /* This is output from LD.  */
  677.  
  678. /* If a this type of symbol is encountered, its name is a warning
  679.    message to print each time the symbol referenced by the next symbol
  680.    table entry is referenced.
  681.  
  682.    This feature may be used to allow backwards compatibility with
  683.    certain functions (eg. gets) but to discourage programmers from
  684.    their use.
  685.  
  686.    So if, for example, you wanted to have ld print a warning whenever
  687.    the function "gets" was used in their C program, you would add the
  688.    following to the assembler file in which gets is defined:
  689.  
  690.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  691.     .stabs "_gets",1,0,0,0
  692.  
  693.    These .stabs do not necessarily have to be in the same file as the
  694.    gets function, they simply must exist somewhere in the compilation.  */
  695.  
  696. #ifndef N_WARNING
  697. #define N_WARNING 0x1E        /* Warning message to print if symbol
  698.                    included */
  699. #endif                /* This is input to ld */
  700.  
  701. #ifndef __GNU_STAB__
  702.  
  703. /* Line number for the data section.  This is to be used to describe
  704.    the source location of a variable declaration.  */
  705. #ifndef N_DSLINE
  706. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  707. #endif
  708.  
  709. /* Line number for the bss section.  This is to be used to describe
  710.    the source location of a variable declaration.  */
  711. #ifndef N_BSLINE
  712. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  713. #endif
  714.  
  715. #endif /* not __GNU_STAB__ */
  716.  
  717. /* Symbol table */
  718.  
  719. /* Global symbol data is recorded in these structures,
  720.    one for each global symbol.
  721.    They are found via hashing in 'symtab', which points to a vector of buckets.
  722.    Each bucket is a chain of these structures through the link field.  */
  723.  
  724. typedef
  725.   struct glosym
  726.     {
  727.       /* Pointer to next symbol in this symbol's hash bucket.  */
  728.       struct glosym *link;
  729.       /* Name of this symbol.  */
  730.       char *name;
  731.       /* Value of this symbol as a global symbol.  */
  732.       long value;
  733.       /* Chain of external 'nlist's in files for this symbol, both defs
  734.      and refs.  */
  735.       struct nlist *refs;
  736.       /* Any warning message that might be associated with this symbol
  737.          from an N_WARNING symbol encountered. */
  738.       char *warning;
  739.       /* Nonzero means definitions of this symbol as common have been seen,
  740.      and the value here is the largest size specified by any of them.  */
  741.       int max_common_size;
  742.       /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
  743.      symbol table to be written, with the first global sym given index 0.*/
  744.       int def_count;
  745.       /* Nonzero means a definition of this global symbol is known to exist.
  746.      Library members should not be loaded on its account.  */
  747.       char defined;
  748.       /* Nonzero means a reference to this global symbol has been seen
  749.      in a file that is surely being loaded.
  750.      A value higher than 1 is the n_type code for the symbol's
  751.      definition.  */
  752.       char referenced;
  753.       /* A count of the number of undefined references printed for a
  754.      specific symbol.  If a symbol is unresolved at the end of
  755.      digest_symbols (and the loading run is supposed to produce
  756.      relocatable output) do_file_warnings keeps track of how many
  757.      unresolved reference error messages have been printed for
  758.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  759.      messages stop. */
  760.       unsigned char undef_refs;
  761.       /* 1 means that this symbol has multiple definitions.  2 means
  762.          that it has multiple definitions, and some of them are set
  763.      elements, one of which has been printed out already.  */
  764.       unsigned char multiply_defined;
  765.       /* Nonzero means print a message at all refs or defs of this symbol */
  766.       char trace;
  767.     }
  768.   symbol;
  769.  
  770. /* Demangler for C++.  */
  771. extern char *cplus_demangle ();
  772.  
  773. /* Demangler function to use.  We unconditionally enable the C++ demangler
  774.    because we assume any name it successfully demangles was probably produced
  775.    by the C++ compiler.  Enabling it only if -lg++ was specified seems too
  776.    much of a kludge.  */
  777. char *(*demangler)() = cplus_demangle;
  778.  
  779. /* Number of buckets in symbol hash table */
  780. #define    TABSIZE    1009
  781.  
  782. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  783. symbol *symtab[TABSIZE];
  784.  
  785. /* Number of symbols in symbol hash table. */
  786. int num_hash_tab_syms = 0;
  787.  
  788. /* Count the number of nlist entries that are for local symbols.
  789.    This count and the three following counts
  790.    are incremented as as symbols are entered in the symbol table.  */
  791. int local_sym_count;
  792.  
  793. /* Count number of nlist entries that are for local symbols
  794.    whose names don't start with L. */
  795. int non_L_local_sym_count;
  796.  
  797. /* Count the number of nlist entries for debugger info.  */
  798. int debugger_sym_count;
  799.  
  800. /* Count the number of global symbols referenced and not defined.  */
  801. int undefined_global_sym_count;
  802.  
  803. /* Count the number of global symbols multiply defined.  */
  804. int multiple_def_count;
  805.  
  806. /* Count the number of defined global symbols.
  807.    Each symbol is counted only once
  808.    regardless of how many different nlist entries refer to it,
  809.    since the output file will need only one nlist entry for it.
  810.    This count is computed by `digest_symbols';
  811.    it is undefined while symbols are being loaded. */
  812. int defined_global_sym_count;
  813.  
  814. /* Count the number of symbols defined through common declarations.
  815.    This count is kept in symdef_library, linear_library, and
  816.    enter_global_ref.  It is incremented when the defined flag is set
  817.    in a symbol because of a common definition, and decremented when
  818.    the symbol is defined "for real" (ie. by something besides a common
  819.    definition).  */
  820. int common_defined_global_count;
  821.  
  822. /* Count the number of set element type symbols and the number of
  823.    separate vectors which these symbols will fit into.  See the
  824.    GNU a.out.h for more info.
  825.    This count is computed by 'enter_file_symbols' */
  826. int set_symbol_count;
  827. int set_vector_count;
  828.  
  829. /* Define a linked list of strings which define symbols which should
  830.    be treated as set elements even though they aren't.  Any symbol
  831.    with a prefix matching one of these should be treated as a set
  832.    element.
  833.  
  834.    This is to make up for deficiencies in many assemblers which aren't
  835.    willing to pass any stabs through to the loader which they don't
  836.    understand.  */
  837. struct string_list_element {
  838.   char *str;
  839.   struct string_list_element *next;
  840. };
  841.  
  842. struct string_list_element *set_element_prefixes;
  843.  
  844. /* Count the number of definitions done indirectly (ie. done relative
  845.    to the value of some other symbol. */
  846. int global_indirect_count;
  847.  
  848. /* Count the number of warning symbols encountered. */
  849. int warning_count;
  850.  
  851. /* Total number of symbols to be written in the output file.
  852.    Computed by digest_symbols from the variables above.  */
  853. int nsyms;
  854.  
  855.  
  856. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  857.    -e sets this.  */
  858. symbol *entry_symbol;
  859.  
  860. /* These can be NULL if we don't actually have such a symbol.  */
  861. symbol *edata_symbol;   /* the symbol _edata */
  862. symbol *etext_symbol;   /* the symbol _etext */
  863. symbol *end_symbol;    /* the symbol _end */
  864. /* We also need __{edata,etext,end} so that they can safely
  865.    be used from an ANSI library.  */
  866. symbol *edata_symbol_alt;
  867. symbol *etext_symbol_alt;
  868. symbol *end_symbol_alt;
  869.  
  870. /* Kinds of files potentially understood by the linker. */
  871.  
  872. enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
  873.  
  874. /* Each input file, and each library member ("subfile") being loaded,
  875.    has a `file_entry' structure for it.
  876.  
  877.    For files specified by command args, these are contained in the vector
  878.    which `file_table' points to.
  879.  
  880.    For library members, they are dynamically allocated,
  881.    and chained through the `chain' field.
  882.    The chain is found in the `subfiles' field of the `file_entry'.
  883.    The `file_entry' objects for the members have `superfile' fields pointing
  884.    to the one for the library.  */
  885.  
  886. struct file_entry {
  887.   /* Name of this file.  */
  888.   char *filename;
  889.  
  890.   /* What kind of file this is. */
  891.   enum file_type file_type;
  892.  
  893.   /* Name to use for the symbol giving address of text start */
  894.   /* Usually the same as filename, but for a file spec'd with -l
  895.      this is the -l switch itself rather than the filename.  */
  896.   char *local_sym_name;
  897.  
  898.   /* Describe the layout of the contents of the file.  */
  899.  
  900.   /* The text section. */
  901.   unsigned long int orig_text_address;
  902.   unsigned long int text_size;
  903.   long int text_offset;
  904.  
  905.   /* Text relocation. */
  906.   unsigned long int text_reloc_size;
  907.   long int text_reloc_offset;
  908.  
  909.   /* The data section. */
  910.   unsigned long int orig_data_address;
  911.   unsigned long int data_size;
  912.   long int data_offset;
  913.  
  914.   /* Data relocation. */
  915.   unsigned long int data_reloc_size;
  916.   long int data_reloc_offset;
  917.  
  918.   /* The bss section. */
  919.   unsigned long int orig_bss_address;
  920.   unsigned long int bss_size;
  921.  
  922.   /* The symbol and string tables. */
  923.   unsigned long int syms_size;
  924.   long int syms_offset;
  925.   unsigned long int strs_size;
  926.   long int strs_offset;
  927.  
  928.   /* The GDB symbol segment, if any. */
  929.   unsigned long int symseg_size;
  930.   long int symseg_offset;
  931.  
  932. #ifdef MACH_O
  933.   /* Section ordinals from the Mach-O load commands.  These
  934.      are compared with the n_sect fields of symbols.  */
  935.   int text_ordinal;
  936.   int data_ordinal;
  937.   int bss_ordinal;
  938. #endif
  939.  
  940.   /* Describe data from the file loaded into core */
  941.  
  942.   /* Symbol table of the file.  */
  943.   struct nlist *symbols;
  944.  
  945.   /* Pointer to the string table.
  946.      The string table is not kept in core all the time,
  947.      but when it is in core, its address is here.  */
  948.   char *strings;
  949.  
  950.   /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
  951.   /* output of undefined reference line numbers. */
  952.  
  953.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  954.   struct relocation_info *textrel;
  955.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  956.   struct relocation_info *datarel;
  957.  
  958.   /* Relation of this file's segments to the output file */
  959.  
  960.   /* Start of this file's text seg in the output file core image.  */
  961.   int text_start_address;
  962.   /* Start of this file's data seg in the output file core image.  */
  963.   int data_start_address;
  964.   /* Start of this file's bss seg in the output file core image.  */
  965.   int bss_start_address;
  966.   /* Offset in bytes in the output file symbol table
  967.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  968.   int local_syms_offset;
  969.  
  970.   /* For library members only */
  971.  
  972.   /* For a library, points to chain of entries for the library members.  */
  973.   struct file_entry *subfiles;
  974.   /* For a library member, offset of the member within the archive.
  975.      Zero for files that are not library members.  */
  976.   int starting_offset;
  977.   /* Size of contents of this file, if library member.  */
  978.   int total_size;
  979.   /* For library member, points to the library's own entry.  */
  980.   struct file_entry *superfile;
  981.   /* For library member, points to next entry for next member.  */
  982.   struct file_entry *chain;
  983.  
  984.   /* 1 if file is a library. */
  985.   char library_flag;
  986.  
  987.   /* 1 if file's header has been read into this structure.  */
  988.   char header_read_flag;
  989.  
  990.   /* 1 means search a set of directories for this file.  */
  991.   char search_dirs_flag;
  992.  
  993.   /* 1 means this is base file of incremental load.
  994.      Do not load this file's text or data.
  995.      Also default text_start to after this file's bss. */
  996.   char just_syms_flag;
  997. };
  998.  
  999. /* Vector of entries for input files specified by arguments.
  1000.    These are all the input files except for members of specified libraries.  */
  1001. struct file_entry *file_table;
  1002.  
  1003. /* Length of that vector.  */
  1004. int number_of_files;
  1005.  
  1006. /* When loading the text and data, we can avoid doing a close
  1007.    and another open between members of the same library.
  1008.  
  1009.    These two variables remember the file that is currently open.
  1010.    Both are zero if no file is open.
  1011.  
  1012.    See `each_file' and `file_close'.  */
  1013.  
  1014. struct file_entry *input_file;
  1015. int input_desc;
  1016.  
  1017. /* The name of the file to write; "a.out" by default.  */
  1018.  
  1019. char *output_filename;
  1020.  
  1021. /* What kind of output file to write.  */
  1022.  
  1023. enum file_type output_file_type;
  1024.  
  1025. #ifndef DEFAULT_OUTPUT_FILE_TYPE
  1026. #ifdef MACH_O
  1027. #define DEFAULT_OUTPUT_FILE_TYPE IS_MACH_O
  1028. #else
  1029. #define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
  1030. #endif
  1031. #endif
  1032.  
  1033. /* What `style' of output file to write.  For BSD a.out files
  1034.    this specifies OMAGIC, NMAGIC, or ZMAGIC.  For Mach-O files
  1035.    this switches between MH_OBJECT and two flavors of MH_EXECUTE.  */
  1036.  
  1037. enum output_style
  1038.   {
  1039.     OUTPUT_UNSPECIFIED,
  1040.     OUTPUT_RELOCATABLE,        /* -r */
  1041.     OUTPUT_WRITABLE_TEXT,    /* -N */
  1042.     OUTPUT_READONLY_TEXT,    /* -n */
  1043.     OUTPUT_DEMAND_PAGED        /* -Z (default) */
  1044.   };
  1045.  
  1046. enum output_style output_style;
  1047.  
  1048. #ifndef DEFAULT_OUTPUT_STYLE
  1049. #define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
  1050. #endif
  1051.  
  1052. /* Descriptor for writing that file with `mywrite'.  */
  1053.  
  1054. int outdesc;
  1055.  
  1056. /* The following are computed by `digest_symbols'.  */
  1057.  
  1058. int text_size;            /* total size of text of all input files.  */
  1059. int text_header_size;        /* size of the file header if included in the
  1060.                    text size.  */
  1061. int data_size;            /* total size of data of all input files.  */
  1062. int bss_size;            /* total size of bss of all input files.  */
  1063. int text_reloc_size;        /* total size of text relocation of all input files.  */
  1064. int data_reloc_size;        /* total size of data relocation of all input
  1065.                    files.  */
  1066.   
  1067. /* The following are computed by write_header().  */
  1068. long int output_text_offset;    /* file offset of the text section.  */
  1069. long int output_data_offset;    /* file offset of the data section.  */
  1070. long int output_trel_offset;    /* file offset of the text relocation info.  */
  1071. long int output_drel_offset;    /* file offset of the data relocation info.  */
  1072. long int output_syms_offset;    /* file offset of the symbol table.  */
  1073. long int output_strs_offset;    /* file offset of the string table.  */
  1074.  
  1075. /* The following are incrementally computed by write_syms(); we keep
  1076.    them here so we can examine their values afterwards.  */
  1077. unsigned int output_syms_size;    /* total bytes of symbol table output. */
  1078. unsigned int output_strs_size;    /* total bytes of string table output. */
  1079.  
  1080. /* This can only be computed after the size of the string table is known.  */
  1081. long int output_symseg_offset;    /* file offset of the symbol segment (if any).  */
  1082.  
  1083. /* Incrementally computed by write_file_symseg().  */
  1084. unsigned int output_symseg_size;
  1085.  
  1086. /* Specifications of start and length of the area reserved at the end
  1087.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  1088. int set_sect_start;
  1089. int set_sect_size;
  1090.  
  1091. /* Pointer for in core storage for the above vectors, before they are
  1092.    written. */
  1093. unsigned long *set_vectors;
  1094.  
  1095. /* Amount of cleared space to leave at the end of the text segment.  */
  1096.  
  1097. int text_pad;
  1098.  
  1099. /* Amount of padding at end of data segment.  This has two parts:
  1100.    That which is before the bss segment, and that which overlaps
  1101.    with the bss segment.  */
  1102. int data_pad;
  1103.  
  1104. /* Format of __.SYMDEF:
  1105.    First, a longword containing the size of the 'symdef' data that follows.
  1106.    Second, zero or more 'symdef' structures.
  1107.    Third, a longword containing the length of symbol name strings.
  1108.    Fourth, zero or more symbol name strings (each followed by a null).  */
  1109.  
  1110. struct symdef {
  1111.   int symbol_name_string_index;
  1112.   int library_member_offset;
  1113. };
  1114.  
  1115. /* Record most of the command options.  */
  1116.  
  1117. /* Address we assume the text section will be loaded at.
  1118.    We relocate symbols and text and data for this, but we do not
  1119.    write any padding in the output file for it.  */
  1120. int text_start;
  1121.  
  1122. /* Address we decide the data section will be loaded at.  */
  1123. int data_start;
  1124.  
  1125. /* Nonzero if -T was specified in the command line.
  1126.    This prevents text_start from being set later to default values.  */
  1127. int T_flag_specified;
  1128.  
  1129. /* Nonzero if -Tdata was specified in the command line.
  1130.    This prevents data_start from being set later to default values.  */
  1131. int Tdata_flag_specified;
  1132.  
  1133. /* Size to pad data section up to.
  1134.    We simply increase the size of the data section, padding with zeros,
  1135.    and reduce the size of the bss section to match.  */
  1136. int specified_data_size;
  1137.  
  1138. #ifdef sprite
  1139. /* Gap to insert between end of bss and start of data seg */
  1140. int data_gap;
  1141.  
  1142. /* Nonzero if -Z was specified (for data_gap) */
  1143. int Z_flag_specified;
  1144. #endif
  1145.  
  1146. /* Nonzero means print names of input files as processed.  */
  1147. int trace_files;
  1148.  
  1149. /* Which symbols should be stripped (omitted from the output):
  1150.    none, all, or debugger symbols.  */
  1151. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  1152.  
  1153. /* Which local symbols should be omitted:
  1154.    none, all, or those starting with L.
  1155.    This is irrelevant if STRIP_NONE.  */
  1156. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  1157.  
  1158. /* 1 => write load map.  */
  1159. int write_map;
  1160.  
  1161. /* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
  1162. int force_common_definition;
  1163.  
  1164. /* Standard directories to search for files specified by -l.  */
  1165. char *standard_search_dirs[] =
  1166. #ifdef STANDARD_SEARCH_DIRS
  1167.   {STANDARD_SEARCH_DIRS};
  1168. #else
  1169. #ifdef NON_NATIVE
  1170.   {"/usr/local/lib/gnu"};
  1171. #else
  1172.   {"/lib", "/usr/lib", "/usr/local/lib"};
  1173. #endif
  1174. #endif
  1175.  
  1176. /* If set STANDARD_SEARCH_DIRS is not searched.  */
  1177. int no_standard_dirs;
  1178.  
  1179. /* Actual vector of directories to search;
  1180.    this contains those specified with -L plus the standard ones.  */
  1181. char **search_dirs;
  1182.  
  1183. /* Length of the vector `search_dirs'.  */
  1184. int n_search_dirs;
  1185.  
  1186. /* Non zero means to create the output executable.
  1187.    Cleared by nonfatal errors.  */
  1188. int make_executable;
  1189.  
  1190. /* Force the executable to be output, even if there are non-fatal
  1191.    errors */
  1192. int force_executable;
  1193.  
  1194. /* Keep a list of any symbols referenced from the command line (so
  1195.    that error messages for these guys can be generated). This list is
  1196.    zero terminated. */
  1197. struct glosym **cmdline_references;
  1198. int cl_refs_allocated;
  1199.  
  1200. #ifndef bcopy
  1201. void bcopy (), bzero ();
  1202. #endif
  1203. char *malloc (), *realloc ();
  1204. void free ();
  1205.  
  1206. char *xmalloc ();
  1207. char *xrealloc ();
  1208. void usage ();
  1209. void fatal ();
  1210. void fatal_with_file ();
  1211. void perror_name ();
  1212. void perror_file ();
  1213. void error ();
  1214.  
  1215. int parse ();
  1216. void initialize_text_start ();
  1217. void initialize_data_start ();
  1218. void digest_symbols ();
  1219. void print_symbols ();
  1220. void load_symbols ();
  1221. void decode_command ();
  1222. void list_undefined_symbols ();
  1223. void list_unresolved_references ();
  1224. void write_output ();
  1225. void write_header ();
  1226. void write_text ();
  1227. void read_file_relocation ();
  1228. void write_data ();
  1229. void write_rel ();
  1230. void write_syms ();
  1231. void write_symsegs ();
  1232. void mywrite ();
  1233. void symtab_init ();
  1234. void padfile ();
  1235. char *concat ();
  1236. char *get_file_name ();
  1237. symbol *getsym (), *getsym_soft ();
  1238.  
  1239. int
  1240. main (argc, argv)
  1241.      char **argv;
  1242.      int argc;
  1243. {
  1244. #ifdef TARGET_PAGE_SIZE
  1245.   page_size = TARGET_PAGE_SIZE;
  1246. #else
  1247.   page_size = getpagesize ();
  1248. #endif
  1249.   progname = argv[0];
  1250.  
  1251. #ifdef RLIMIT_STACK
  1252.   /* Avoid dumping core on large .o files.  */
  1253.   {
  1254.     struct rlimit rl;
  1255.  
  1256.     getrlimit (RLIMIT_STACK, &rl);
  1257.     rl.rlim_cur = rl.rlim_max;
  1258.     setrlimit (RLIMIT_STACK, &rl);
  1259.   }
  1260. #endif
  1261.  
  1262.   /* Clear the cumulative info on the output file.  */
  1263.  
  1264.   text_size = 0;
  1265.   data_size = 0;
  1266.   bss_size = 0;
  1267.   text_reloc_size = 0;
  1268.   data_reloc_size = 0;
  1269.  
  1270.   data_pad = 0;
  1271.   text_pad = 0;
  1272.  
  1273.   /* Initialize the data about options.  */
  1274.  
  1275.   specified_data_size = 0;
  1276.   strip_symbols = STRIP_NONE;
  1277.   trace_files = 0;
  1278.   discard_locals = DISCARD_NONE;
  1279.   entry_symbol = 0;
  1280.   write_map = 0;
  1281.   force_common_definition = 0;
  1282.   T_flag_specified = 0;
  1283.   Tdata_flag_specified = 0;
  1284.   make_executable = 1;
  1285.   force_executable = 0;
  1286.   set_element_prefixes = 0;
  1287.   Z_flag_specified = 0;
  1288.  
  1289.   /* Initialize the cumulative counts of symbols.  */
  1290.  
  1291.   local_sym_count = 0;
  1292.   non_L_local_sym_count = 0;
  1293.   debugger_sym_count = 0;
  1294.   undefined_global_sym_count = 0;
  1295.   set_symbol_count = 0;
  1296.   set_vector_count = 0;
  1297.   global_indirect_count = 0;
  1298.   warning_count = 0;
  1299.   multiple_def_count = 0;
  1300.   common_defined_global_count = 0;
  1301.  
  1302.   /* Keep a list of symbols referenced from the command line */
  1303.  
  1304.   cl_refs_allocated = 10;
  1305.   cmdline_references =
  1306.     (struct glosym **) xmalloc (cl_refs_allocated
  1307.                   * sizeof(struct glosym *));
  1308.   *cmdline_references = 0;
  1309.  
  1310.   /* Completely decode ARGV.  */
  1311.  
  1312.   decode_command (argc, argv);
  1313.  
  1314.   /* Load symbols of all input files.
  1315.      Also search all libraries and decide which library members to load.  */
  1316.  
  1317.   load_symbols ();
  1318.  
  1319.   /* Create various built-in symbols.  This must occur after
  1320.      all input files are loaded so that a user program can have a
  1321.      symbol named etext (for example).  */
  1322.  
  1323.   if (output_style != OUTPUT_RELOCATABLE)
  1324.     symtab_init ();
  1325.  
  1326.   /* Compute where each file's sections go, and relocate symbols.  */
  1327.  
  1328.   digest_symbols ();
  1329.  
  1330.   /* Print error messages for any missing symbols, for any warning
  1331.      symbols, and possibly multiple definitions */
  1332.  
  1333.   do_warnings (stderr);
  1334.  
  1335.   /* Print a map, if requested.  */
  1336.  
  1337.   if (write_map) print_symbols (stdout);
  1338.  
  1339.   /* Write the output file.  */
  1340.  
  1341.   if (make_executable || force_executable)
  1342.     write_output ();
  1343.  
  1344.   exit (!make_executable);
  1345. }
  1346.  
  1347. void add_cmdline_ref ();
  1348.  
  1349. static struct option longopts[] =
  1350. {
  1351.   {"d", 0, 0, 'd'},
  1352.   {"dc", 0, 0, 'd'},        /* For Sun compatibility. */
  1353.   {"dp", 0, 0, 'd'},        /* For Sun compatibility. */
  1354.   {"e", 1, 0, 'e'},
  1355.   {"n", 0, 0, 'n'},
  1356.   {"noinhibit-exec", 0, 0, 130},
  1357.   {"nostdlib", 0, 0, 133},
  1358.   {"o", 1, 0, 'o'},
  1359.   {"r", 0, 0, 'r'},
  1360.   {"s", 0, 0, 's'},
  1361.   {"t", 0, 0, 't'},
  1362.   {"u", 1, 0, 'u'},
  1363.   {"x", 0, 0, 'x'},
  1364.   {"z", 0, 0, 'z'},
  1365.   {"A", 1, 0, 'A'},
  1366.   {"Bstatic", 0, 0, 129},    /* For Sun compatibility. */
  1367.   {"D", 1, 0, 'D'},
  1368.   {"M", 0, 0, 'M'},
  1369.   {"N", 0, 0, 'N'},
  1370.   {"S", 0, 0, 'S'},
  1371.   {"T", 1, 0, 'T'},
  1372.   {"Ttext", 1, 0, 'T'},
  1373.   {"Tdata", 1, 0, 132},
  1374.   {"V", 1, 0, 'V'},
  1375.   {"X", 0, 0, 'X'},
  1376.   {0, 0, 0, 0}
  1377. };
  1378.  
  1379. /* Since the Unix ld accepts -lfoo, -Lfoo, and -yfoo, we must also.
  1380.    This effectively prevents any long options from starting with
  1381.    one of these letters. */
  1382. #define SHORTOPTS "-l:y:L:"
  1383.  
  1384. /* Process the command arguments,
  1385.    setting up file_table with an entry for each input file,
  1386.    and setting variables according to the options.  */
  1387.  
  1388. void
  1389. decode_command (argc, argv)
  1390.      char **argv;
  1391.      int argc;
  1392. {
  1393.   int optc, longind;
  1394.   register struct file_entry *p;
  1395.  
  1396.   number_of_files = 0;
  1397.   output_filename = "a.out";
  1398.  
  1399.   n_search_dirs = 0;
  1400.   search_dirs = (char **) xmalloc (sizeof (char *));
  1401.  
  1402.   /* First compute number_of_files so we know how long to make file_table.
  1403.      Also process most options completely.  */
  1404.  
  1405.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1406.      != EOF)
  1407.     {
  1408.       if (optc == 0)
  1409.     optc = longopts[longind].val;
  1410.  
  1411.       switch (optc)
  1412.     {
  1413.     case '?':
  1414.       usage (0, 0);
  1415.       break;
  1416.  
  1417.     case 1:
  1418.       /* Non-option argument. */
  1419.       number_of_files++;
  1420.       break;
  1421.  
  1422.     case 'd':
  1423.       force_common_definition = 1;
  1424.       break;
  1425.  
  1426.     case 'e':
  1427.       entry_symbol = getsym (optarg);
  1428.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1429.         undefined_global_sym_count++;
  1430.       entry_symbol->referenced = 1;
  1431.       add_cmdline_ref (entry_symbol);
  1432.       break;
  1433.  
  1434. #if TARGET==TARGET_SEQUENT
  1435.       /*
  1436.        * k == Symmetry standalone,
  1437.        */
  1438.         case 'k':
  1439. #ifdef SMAGIC
  1440.       magic = SMAGIC;
  1441. #else
  1442.       fatal("No SMAGIC defined for -k");
  1443. #endif
  1444.       return;
  1445. #endif
  1446.  
  1447.     case 'l':
  1448.       number_of_files++;
  1449.       break;
  1450.  
  1451.     case 'n':
  1452.       if (output_style && output_style != OUTPUT_READONLY_TEXT)
  1453.         fatal ("illegal combination of -n with -N, -r, or -z", (char *) 0);
  1454.       output_style = OUTPUT_READONLY_TEXT;
  1455.       break;
  1456.  
  1457.     case 130:        /* -noinhibit-exec */
  1458.       force_executable = 1;
  1459.       break;
  1460.  
  1461.     case 133:        /* -nostdlib */
  1462.       no_standard_dirs = 1;
  1463.       break;
  1464.  
  1465.     case 'o':
  1466.       output_filename = optarg;
  1467.       break;
  1468.  
  1469. #if TARGET==TARGET_SEQUENT
  1470.       /*
  1471.        * p == don't align text/data boundary (for 8K disk bootstraps).
  1472.        */
  1473.          case 'p':
  1474.        break;
  1475. #endif
  1476.  
  1477.     case 'r':
  1478.       if (output_style && output_style != OUTPUT_RELOCATABLE)
  1479.         fatal ("illegal combination of -r with -N, -n, or -z", (char *) 0);
  1480.       output_style = OUTPUT_RELOCATABLE;
  1481.       text_start = 0;
  1482.       break;
  1483.  
  1484.     case 's':
  1485.       strip_symbols = STRIP_ALL;
  1486.       break;
  1487.  
  1488.     case 't':
  1489.       trace_files = 1;
  1490.       break;
  1491.  
  1492.     case 'u':
  1493.       {
  1494.         register symbol *sp = getsym (optarg);
  1495.  
  1496.         if (!sp->defined && !sp->referenced)
  1497.           undefined_global_sym_count++;
  1498.         sp->referenced = 1;
  1499.         add_cmdline_ref (sp);
  1500.       }
  1501.       break;
  1502.  
  1503.     case 'x':
  1504.       discard_locals = DISCARD_ALL;
  1505.       break;
  1506.  
  1507.     case 'y':
  1508.       {
  1509.         register symbol *sp = getsym (optarg);
  1510.  
  1511.         sp->trace = 1;
  1512.       }
  1513.       break;
  1514.  
  1515.     case 'z':
  1516.       if (output_style && output_style != OUTPUT_DEMAND_PAGED)
  1517.         fatal ("illegal combination of -z with -N, -n, or -r", (char *) 0);
  1518.       output_style = OUTPUT_DEMAND_PAGED;
  1519.       break;
  1520.  
  1521.     case 'A':
  1522.       number_of_files++;
  1523.       break;
  1524.  
  1525.     case 129:        /* -Bstatic. */
  1526.       /* Ignore. */
  1527.       break;
  1528.  
  1529.     case 'D':
  1530.       specified_data_size = parse (optarg, "%x", "invalid argument to -D");
  1531.       break;
  1532.  
  1533.     case 'L':
  1534.       n_search_dirs++;
  1535.       search_dirs = (char **)
  1536.         xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1537.       search_dirs[n_search_dirs - 1] = optarg;
  1538.       break;
  1539.  
  1540.     case 'M':
  1541.       write_map = 1;
  1542.       break;
  1543.  
  1544.     case 'N':
  1545.       if (output_style && output_style != OUTPUT_WRITABLE_TEXT)
  1546.         fatal ("illegal combination of -N with -n, -r, or -z", (char *) 0);
  1547.       output_style = OUTPUT_WRITABLE_TEXT;
  1548.       break;
  1549.  
  1550.     case 'S':
  1551.       strip_symbols = STRIP_DEBUGGER;
  1552.       break;
  1553.  
  1554.         case 'T':
  1555.       text_start = parse (optarg, "%x", "invalid argument to -Ttext");
  1556.       T_flag_specified = 1;
  1557. #ifdef sprite
  1558.       output_style = OUTPUT_WRITABLE_TEXT;
  1559. #endif
  1560.       break;
  1561.  
  1562.     case 132:        /* -Tdata addr */
  1563.       data_start = parse (optarg, "%x", "invalid argument to -Tdata");
  1564.       Tdata_flag_specified = 1;
  1565.       break;
  1566.  
  1567.     case 'V':
  1568.       {
  1569.         struct string_list_element *new
  1570.           = (struct string_list_element *)
  1571.         xmalloc (sizeof (struct string_list_element));
  1572.  
  1573.         new->str = optarg;
  1574.         new->next = set_element_prefixes;
  1575.         set_element_prefixes = new;
  1576.       }
  1577.       break;
  1578.  
  1579.     case 'X':
  1580.       discard_locals = DISCARD_L;
  1581.       break;
  1582.  
  1583.     }
  1584.     }
  1585.  
  1586.   if (!number_of_files)
  1587.     usage ("no input files", 0);
  1588.  
  1589.   p = file_table
  1590.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1591.   bzero (p, number_of_files * sizeof (struct file_entry));
  1592.  
  1593.   /* Now scan again and fill in file_table.
  1594.      All options except -A and -l are ignored here.  */
  1595.  
  1596.   optind = 0;            /* Reset getopt. */
  1597.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1598.      != EOF)
  1599.     {
  1600.       if (optc == 0)
  1601.     optc = longopts[longind].val;
  1602.  
  1603.       switch (optc)
  1604.     {
  1605.     case 1:
  1606.       /* Non-option argument. */
  1607.       p->filename = optarg;
  1608.       p->local_sym_name = optarg;
  1609.       p++;
  1610.       break;
  1611.  
  1612.     case 'A':
  1613.       if (p != file_table)
  1614.         usage ("-A specified before an input file other than the first");
  1615.       p->filename = optarg;
  1616.       p->local_sym_name = optarg;
  1617.       p->just_syms_flag = 1;
  1618.       p++;
  1619.       break;
  1620.  
  1621.     case 'l':
  1622.       p->filename = concat ("lib", optarg, ".a");
  1623.       p->local_sym_name = concat ("-l", optarg, "");
  1624.       p->search_dirs_flag = 1;
  1625.       p++;
  1626.       break;
  1627.     }
  1628.     }
  1629.  
  1630.   if (!output_file_type)
  1631.     output_file_type = DEFAULT_OUTPUT_FILE_TYPE;
  1632.  
  1633.   if (!output_style)
  1634.     output_style = DEFAULT_OUTPUT_STYLE;
  1635.  
  1636. #if 0
  1637.   /* THIS CONSISTENCY CHECK BELONGS SOMEWHERE ELSE.  */
  1638.   /* Now check some option settings for consistency.  */
  1639.  
  1640.   if ((output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  1641.       && (text_start - text_start_alignment) & (page_size - 1))
  1642.     usage ("-T argument not multiple of page size, with sharable output", 0);
  1643. #endif
  1644.  
  1645.   /* Append the standard search directories to the user-specified ones.  */
  1646.   if (!no_standard_dirs)
  1647.     {
  1648.       int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1649.       n_search_dirs += n;
  1650.       search_dirs
  1651.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1652.       bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1653.          n * sizeof (char *));
  1654.     }
  1655. }
  1656.  
  1657.  
  1658. void
  1659. add_cmdline_ref (sp)
  1660.      struct glosym *sp;
  1661. {
  1662.   struct glosym **ptr;
  1663.  
  1664.   for (ptr = cmdline_references;
  1665.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1666.        ptr++)
  1667.     ;
  1668.  
  1669.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1670.     {
  1671.       int diff = ptr - cmdline_references;
  1672.  
  1673.       cl_refs_allocated *= 2;
  1674.       cmdline_references = (struct glosym **)
  1675.     xrealloc (cmdline_references,
  1676.          cl_refs_allocated * sizeof (struct glosym *));
  1677.       ptr = cmdline_references + diff;
  1678.     }
  1679.  
  1680.   *ptr++ = sp;
  1681.   *ptr = (struct glosym *) 0;
  1682. }
  1683.  
  1684. int
  1685. set_element_prefixed_p (name)
  1686.      char *name;
  1687. {
  1688.   struct string_list_element *p;
  1689.   int i;
  1690.  
  1691.   for (p = set_element_prefixes; p; p = p->next)
  1692.     {
  1693.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1694.     ;
  1695.  
  1696.       if (p->str[i] == '\0')
  1697.     return 1;
  1698.     }
  1699.   return 0;
  1700. }
  1701.  
  1702. /* Convenient functions for operating on one or all files being
  1703.    loaded.  */
  1704. void print_file_name ();
  1705.  
  1706. /* Call FUNCTION on each input file entry.
  1707.    Do not call for entries for libraries;
  1708.    instead, call once for each library member that is being loaded.
  1709.  
  1710.    FUNCTION receives two arguments: the entry, and ARG.  */
  1711.  
  1712. void
  1713. each_file (function, arg)
  1714.      register void (*function)();
  1715.      register int arg;
  1716. {
  1717.   register int i;
  1718.  
  1719.   for (i = 0; i < number_of_files; i++)
  1720.     {
  1721.       register struct file_entry *entry = &file_table[i];
  1722.       if (entry->library_flag)
  1723.         {
  1724.       register struct file_entry *subentry = entry->subfiles;
  1725.       for (; subentry; subentry = subentry->chain)
  1726.         (*function) (subentry, arg);
  1727.     }
  1728.       else
  1729.     (*function) (entry, arg);
  1730.     }
  1731. }
  1732. #if 0
  1733. /* Call FUNCTION on each input file entry until it returns a non-zero
  1734.    value.  Return this value.
  1735.    Do not call for entries for libraries;
  1736.    instead, call once for each library member that is being loaded.
  1737.  
  1738.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1739.    function returning unsigned long (though this can probably be fudged). */
  1740.  
  1741. unsigned long
  1742. check_each_file (function, arg)
  1743.      register unsigned long (*function)();
  1744.      register int arg;
  1745. {
  1746.   register int i;
  1747.   register unsigned long return_val;
  1748.  
  1749.   for (i = 0; i < number_of_files; i++)
  1750.     {
  1751.       register struct file_entry *entry = &file_table[i];
  1752.       if (entry->library_flag)
  1753.         {
  1754.       register struct file_entry *subentry = entry->subfiles;
  1755.       for (; subentry; subentry = subentry->chain)
  1756.         if (return_val = (*function) (subentry, arg))
  1757.           return return_val;
  1758.     }
  1759.       else
  1760.     if (return_val = (*function) (entry, arg))
  1761.       return return_val;
  1762.     }
  1763.   return 0;
  1764. }
  1765. #endif
  1766. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1767.  
  1768. void
  1769. each_full_file (function, arg)
  1770.      register void (*function)();
  1771.      register int arg;
  1772. {
  1773.   register int i;
  1774.  
  1775.   for (i = 0; i < number_of_files; i++)
  1776.     {
  1777.       register struct file_entry *entry = &file_table[i];
  1778.       if (entry->just_syms_flag)
  1779.     continue;
  1780.       if (entry->library_flag)
  1781.         {
  1782.       register struct file_entry *subentry = entry->subfiles;
  1783.       for (; subentry; subentry = subentry->chain)
  1784.         (*function) (subentry, arg);
  1785.     }
  1786.       else
  1787.     (*function) (entry, arg);
  1788.     }
  1789. }
  1790.  
  1791. /* Close the input file that is now open.  */
  1792.  
  1793. void
  1794. file_close ()
  1795. {
  1796.   close (input_desc);
  1797.   input_desc = 0;
  1798.   input_file = 0;
  1799. }
  1800.  
  1801. /* Open the input file specified by 'entry', and return a descriptor.
  1802.    The open file is remembered; if the same file is opened twice in a row,
  1803.    a new open is not actually done.  */
  1804.  
  1805. int
  1806. file_open (entry)
  1807.      register struct file_entry *entry;
  1808. {
  1809.   register int desc;
  1810.  
  1811.   if (entry->superfile)
  1812.     return file_open (entry->superfile);
  1813.  
  1814.   if (entry == input_file)
  1815.     return input_desc;
  1816.  
  1817.   if (input_file) file_close ();
  1818.  
  1819.   if (entry->search_dirs_flag && n_search_dirs)
  1820.     {
  1821.       int i;
  1822.  
  1823.       for (i = 0; i < n_search_dirs; i++)
  1824.     {
  1825.       register char *string
  1826.         = concat (search_dirs[i], "/", entry->filename);
  1827.       desc = open (string, O_RDONLY, 0);
  1828.       if (desc > 0)
  1829.         {
  1830.           entry->filename = string;
  1831.           entry->search_dirs_flag = 0;
  1832.           break;
  1833.         }
  1834.       free (string);
  1835.     }
  1836.     }
  1837.   else
  1838.     desc = open (entry->filename, O_RDONLY, 0);
  1839.  
  1840.   if (desc > 0)
  1841.     {
  1842.       input_file = entry;
  1843.       input_desc = desc;
  1844.       return desc;
  1845.     }
  1846.  
  1847.   perror_file (entry);
  1848.   /* NOTREACHED */
  1849. }
  1850.  
  1851. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1852.    and then a newline.  */
  1853.  
  1854. void
  1855. prline_file_name (entry, outfile)
  1856.      struct file_entry *entry;
  1857.      FILE *outfile;
  1858. {
  1859.   print_file_name (entry, outfile);
  1860.   fprintf (outfile, "\n");
  1861. }
  1862.  
  1863. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1864.  
  1865. void
  1866. print_file_name (entry, outfile)
  1867.      struct file_entry *entry;
  1868.      FILE *outfile;
  1869. {
  1870.   if (entry->superfile)
  1871.     {
  1872.       print_file_name (entry->superfile, outfile);
  1873.       fprintf (outfile, "(%s)", entry->filename);
  1874.     }
  1875.   else
  1876.     fprintf (outfile, "%s", entry->filename);
  1877. }
  1878.  
  1879. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1880.  
  1881. char *
  1882. get_file_name (entry)
  1883.      struct file_entry *entry;
  1884. {
  1885.   char *result, *supfile;
  1886.   if (entry->superfile)
  1887.     {
  1888.       supfile = get_file_name (entry->superfile);
  1889.       result = (char *) xmalloc (strlen (supfile)
  1890.                  + strlen (entry->filename) + 3);
  1891.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1892.       free (supfile);
  1893.     }
  1894.   else
  1895.     {
  1896.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1897.       strcpy (result, entry->filename);
  1898.     }
  1899.   return result;
  1900. }
  1901.  
  1902. /* Medium-level input routines for rel files.  */
  1903.  
  1904. /* Determine whether the given ENTRY is an archive, a BSD a.out file,
  1905.    a Mach-O file, or whatever.  DESC is the descriptor on which the
  1906.    file is open.  */
  1907. void
  1908. deduce_file_type(desc, entry)
  1909.      int desc;
  1910.      struct file_entry *entry;
  1911. {
  1912.   int len;
  1913.  
  1914.   {
  1915.     char magic[SARMAG];
  1916.     
  1917.     lseek (desc, entry->starting_offset, 0);
  1918.     len = read (desc, magic, SARMAG);
  1919.     if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
  1920.       {
  1921.     entry->file_type = IS_ARCHIVE;
  1922.     return;
  1923.       }
  1924.   }
  1925.  
  1926. #ifdef A_OUT
  1927.   {
  1928.     struct exec hdr;
  1929.  
  1930.     lseek (desc, entry->starting_offset, 0);
  1931. #ifdef COFF_ENCAPSULATE
  1932.     if (entry->just_syms_flag)
  1933.       /* Since a file given with -A will have a coff header, unlike normal
  1934.     input files, we need to skip over it.  */
  1935.       lseek (desc, sizeof (coffheader), SEEK_CUR);
  1936. #endif
  1937.     len = read (desc, (char *) &hdr, sizeof (struct exec));
  1938. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  1939.   fix_exec_header_byte_order(&hdr);
  1940. #endif
  1941.     if (len == sizeof (struct exec) && !N_BADMAG (hdr))
  1942.       {
  1943.     entry->file_type = IS_A_OUT;
  1944.     return;
  1945.       }
  1946.   }
  1947. #endif
  1948.  
  1949. #ifdef MACH_O
  1950.   {
  1951.     struct mach_header hdr;
  1952.  
  1953.     lseek (desc, entry->starting_offset, 0);
  1954.     len = read (desc, (char *) &hdr, sizeof (struct mach_header));
  1955.     if (len == sizeof (struct mach_header) && hdr.magic == MH_MAGIC)
  1956.       {
  1957.     entry->file_type = IS_MACH_O;
  1958.     return;
  1959.       }
  1960.   }
  1961. #endif
  1962.  
  1963.   fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1964. }
  1965.  
  1966. #ifdef A_OUT
  1967. /* Read an a.out file's header and set up the fields of
  1968.    the ENTRY accordingly.  DESC is the descriptor on which
  1969.    the file is open.  */
  1970. void
  1971. read_a_out_header (desc, entry)
  1972.      int desc;
  1973.      struct file_entry *entry;
  1974. {
  1975.   register int len;
  1976.   struct exec hdr;
  1977.   struct stat st;
  1978.  
  1979.   lseek (desc, entry->starting_offset, 0);
  1980.  
  1981. #ifdef COFF_ENCAPSULATE
  1982.   if (entry->just_syms_flag)
  1983.     /* Since a file given with -A will have a coff header, unlike normal
  1984.        input files, we need to skip over it.  */
  1985.     lseek (desc, sizeof (coffheader), SEEK_CUR);
  1986. #endif
  1987.  
  1988.   read (desc, (char *) &hdr, sizeof (struct exec));
  1989.  
  1990. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  1991.   fix_exec_header_byte_order(&hdr);
  1992. #endif
  1993.  
  1994. #ifdef READ_HEADER_HOOK
  1995.   READ_HEADER_HOOK(hdr.a_machtype);
  1996. #endif
  1997.  
  1998.   if (entry->just_syms_flag)
  1999.     entry->orig_text_address = N_TXTADDR(hdr);
  2000.   else
  2001.     entry->orig_text_address = 0;
  2002.   entry->text_size = hdr.a_text;
  2003.   entry->text_offset = N_TXTOFF(hdr);
  2004.  
  2005.   entry->text_reloc_size = hdr.a_trsize;
  2006. #ifdef N_TRELOFF
  2007.   entry->text_reloc_offset = N_TRELOFF(hdr);
  2008. #else
  2009. #ifdef N_DATOFF
  2010.   entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
  2011. #else
  2012.   entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
  2013. #endif
  2014. #endif
  2015.  
  2016.   if (entry->just_syms_flag)
  2017.     entry->orig_data_address = N_DATADDR(hdr);
  2018.   else
  2019.     entry->orig_data_address = entry->text_size;
  2020.   entry->data_size = hdr.a_data;
  2021. #ifdef N_DATOFF
  2022.   entry->data_offset = N_DATOFF(hdr);
  2023. #else
  2024.   entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
  2025. #endif
  2026.  
  2027.   entry->data_reloc_size = hdr.a_drsize;
  2028. #ifdef N_DRELOFF
  2029.   entry->data_reloc_offset = N_DRELOFF(hdr);
  2030. #else
  2031.   entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
  2032. #endif
  2033.  
  2034. #ifdef N_BSSADDR
  2035.   if (entry->just_syms_flag)
  2036.     entry->orig_bss_address = N_BSSADDR(hdr);
  2037.   else
  2038. #endif
  2039.   entry->orig_bss_address = entry->orig_data_address + entry->data_size;
  2040.   entry->bss_size = hdr.a_bss;
  2041.  
  2042.   entry->syms_size = hdr.a_syms;
  2043.   entry->syms_offset = N_SYMOFF(hdr);
  2044.   entry->strs_offset = N_STROFF(hdr);
  2045.   lseek(desc, entry->starting_offset + entry->strs_offset, 0);
  2046.   if (read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
  2047.       != sizeof (unsigned long int))
  2048.     fatal_with_file ("failure reading string table size of ", entry);
  2049.  
  2050. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2051.   fix_byte_order(&entry->strs_size, sizeof (unsigned long int));
  2052. #endif
  2053.  
  2054.   if (!entry->superfile)
  2055.     {
  2056.       fstat(desc, &st);
  2057.       if (st.st_size > entry->strs_offset + entry->strs_size)
  2058.     {
  2059.       entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
  2060.       entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2061.     }
  2062.     }
  2063.   else
  2064.     if (entry->total_size > entry->strs_offset + entry->strs_size)
  2065.       {
  2066.     entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
  2067.     entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2068.       }
  2069. }
  2070. #endif
  2071.  
  2072. #ifdef MACH_O
  2073. /* Read a Mach-O file's header.  DESC is the descriptor on which the
  2074.    file is open, and ENTRY is the file's entry.  */
  2075. void
  2076. read_mach_o_header (desc, entry)
  2077.      int desc;
  2078.      struct file_entry *entry;
  2079. {
  2080.   struct mach_header mach_header;
  2081.   char *hdrbuf;
  2082.   struct load_command *load_command;
  2083.   struct segment_command *segment_command;
  2084.   struct section *section;
  2085.   struct symtab_command *symtab_command;
  2086. #ifdef LC_SYMSEG
  2087.   struct symseg_command *symseg_command;
  2088. #endif;
  2089.   int ordinal;
  2090.   int symtab_seen, symseg_seen;
  2091.   int len, cmd, seg;
  2092.  
  2093.   entry->text_ordinal = entry->data_ordinal = entry->bss_ordinal = 0;
  2094.   symtab_seen = symseg_seen = 0;
  2095.   ordinal = 1;
  2096.  
  2097.   lseek (desc, entry->starting_offset, 0);
  2098.   len = read (desc, (char *) &mach_header, sizeof (struct mach_header));
  2099.   if (len != sizeof (struct mach_header))
  2100.     fatal_with_file ("failure reading Mach-O header of ", entry);
  2101.   if (mach_header.filetype != MH_OBJECT && mach_header.filetype != MH_EXECUTE)
  2102.     fatal_with_file ("unsupported Mach-O file type (not MH_OBJECT or MH_EXECUTE) in ", entry);
  2103.   hdrbuf = xmalloc (mach_header.sizeofcmds);
  2104.   len = read (desc, hdrbuf, mach_header.sizeofcmds);
  2105.   if (len != mach_header.sizeofcmds)
  2106.     fatal_with_file ("failure reading Mach-O load commands of ", entry);
  2107.   load_command = (struct load_command *) hdrbuf;
  2108.   for (cmd = 0; cmd < mach_header.ncmds; ++cmd)
  2109.     {
  2110.       switch (load_command->cmd)
  2111.     {
  2112.     case LC_SEGMENT:
  2113.       segment_command = (struct segment_command *) load_command;
  2114.       section = (struct section *) ((char *) (segment_command + 1));
  2115.       for (seg = 0; seg < segment_command->nsects; ++seg, ++section, ++ordinal)
  2116.         {
  2117.           if (!strncmp(SECT_TEXT, section->sectname, sizeof section->sectname))
  2118.         if (entry->text_ordinal)
  2119.           fatal_with_file ("more than one __text section in ", entry);
  2120.         else
  2121.           {
  2122.             entry->text_ordinal = ordinal;
  2123.             entry->orig_text_address = section->addr;
  2124.             entry->text_size = section->size;
  2125.             entry->text_offset = section->offset;
  2126.             entry->text_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2127.             entry->text_reloc_offset = section->reloff;
  2128.           }
  2129.           else if (!strncmp(SECT_DATA, section->sectname, sizeof section->sectname))
  2130.         if (entry->data_ordinal)
  2131.           fatal_with_file ("more than one __data section in ", entry);
  2132.         else
  2133.           {
  2134.             entry->data_ordinal = ordinal;
  2135.             entry->orig_data_address = section->addr;
  2136.             entry->data_size = section->size;
  2137.             entry->data_offset = section->offset;
  2138.             entry->data_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2139.             entry->data_reloc_offset = section->reloff;
  2140.           }
  2141.           else if (!strncmp(SECT_BSS, section->sectname, sizeof section->sectname))
  2142.         if (entry->bss_ordinal)
  2143.           fatal_with_file ("more than one __bss section in ", entry);
  2144.         else
  2145.           {
  2146.             entry->bss_ordinal = ordinal;
  2147.             entry->orig_bss_address = section->addr;
  2148.             entry->bss_size = section->size;
  2149.           }
  2150.           else
  2151.         if (section->size != 0)
  2152.           fprintf (stderr, "%s: warning: unknown section `%.*s' in %s\n",
  2153.                progname, sizeof section->sectname, section->sectname,
  2154.                entry->filename);
  2155.         }
  2156.       break;
  2157.     case LC_SYMTAB:
  2158.       if (symtab_seen)
  2159.           fatal_with_file ("more than one LC_SYMTAB in ", entry);
  2160.       else
  2161.         {
  2162.           symtab_seen = 1;
  2163.           symtab_command = (struct symtab_command *) load_command;
  2164.           entry->syms_size = symtab_command->nsyms * sizeof (struct nlist);
  2165.           entry->syms_offset = symtab_command->symoff;
  2166.           entry->strs_size = symtab_command->strsize;
  2167.           entry->strs_offset = symtab_command->stroff;
  2168.         }
  2169.       break;
  2170. #ifdef LC_SYMSEG
  2171.     case LC_SYMSEG:
  2172.       if (symseg_seen)
  2173.         fatal_with_file ("more than one LC_SYMSEG in ", entry);
  2174.       else
  2175.         {
  2176.           symseg_seen = 1;
  2177.           symseg_command = (struct symseg_command *) load_command;
  2178.           entry->symseg_size = symseg_command->size;
  2179.           entry->symseg_offset = symseg_command->offset;
  2180.         }
  2181.       break;
  2182. #endif
  2183.     }
  2184.       load_command = (struct load_command *)
  2185.     ((char *) load_command + load_command->cmdsize);
  2186.     }
  2187.  
  2188.   free (hdrbuf);
  2189.  
  2190.   if (!symtab_seen)
  2191.     fprintf (stderr, "%s: no symbol table in %s\n", progname, entry->filename);
  2192. }
  2193. #endif
  2194.  
  2195. /* Read a file's header info into the proper place in the file_entry.
  2196.    DESC is the descriptor on which the file is open.
  2197.    ENTRY is the file's entry.
  2198.    Switch in the file_type to determine the appropriate actual
  2199.    header reading routine to call.  */
  2200.  
  2201. void
  2202. read_header (desc, entry)
  2203.      int desc;
  2204.      register struct file_entry *entry;
  2205. {
  2206.   if (!entry->file_type)
  2207.     deduce_file_type (desc, entry);
  2208.  
  2209.   switch (entry->file_type)
  2210.     {
  2211.     case IS_ARCHIVE:
  2212.     default:
  2213.       /* Should never happen. */
  2214.       abort ();
  2215.  
  2216. #ifdef A_OUT
  2217.     case IS_A_OUT:
  2218.       read_a_out_header (desc, entry);
  2219.       break;
  2220. #endif
  2221.  
  2222. #ifdef MACH_O
  2223.     case IS_MACH_O:
  2224.       read_mach_o_header (desc, entry);
  2225.       break;
  2226. #endif
  2227.     }
  2228.  
  2229.   entry->header_read_flag = 1;
  2230. }
  2231.  
  2232. #ifdef MACH_O
  2233. void translate_mach_o_symbols ();
  2234. #endif
  2235.  
  2236. /* Read the symbols of file ENTRY into core.
  2237.    Assume it is already open, on descriptor DESC.  */
  2238.  
  2239. void
  2240. read_entry_symbols (desc, entry)
  2241.      struct file_entry *entry;
  2242.      int desc;
  2243. {
  2244.   int str_size;
  2245.  
  2246.   if (!entry->header_read_flag)
  2247.     read_header (desc, entry);
  2248.  
  2249.   entry->symbols = (struct nlist *) xmalloc (entry->syms_size);
  2250.  
  2251.   lseek (desc, entry->syms_offset + entry->starting_offset, 0);
  2252.   if (entry->syms_size != read (desc, entry->symbols, entry->syms_size))
  2253.     fatal_with_file ("premature end of file in symbols of ", entry);
  2254.  
  2255. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2256.   fix_symbol_byte_order(entry->symbols, entry->syms_size);
  2257. #endif
  2258.  
  2259. #ifdef MACH_O
  2260.   if (entry->file_type == IS_MACH_O)
  2261.     translate_mach_o_symbols (entry);
  2262. #endif
  2263. }
  2264.  
  2265. /* Read the string table of file ENTRY into core.
  2266.    Assume it is already open, on descriptor DESC.  */
  2267.  
  2268. void
  2269. read_entry_strings (desc, entry)
  2270.      struct file_entry *entry;
  2271.      int desc;
  2272. {
  2273.   int buffer;
  2274.  
  2275.   if (!entry->header_read_flag)
  2276.     read_header (desc, entry);
  2277.  
  2278.   lseek (desc, entry->strs_offset + entry->starting_offset, 0);
  2279.   if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
  2280.     fatal_with_file ("premature end of file in strings of ", entry);
  2281. }
  2282.  
  2283. /* Read in the symbols of all input files.  */
  2284.  
  2285. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  2286. void enter_file_symbols (), enter_global_ref (), search_library ();
  2287.  
  2288. void
  2289. load_symbols ()
  2290. {
  2291.   register int i;
  2292.  
  2293.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  2294.  
  2295.   for (i = 0; i < number_of_files; i++)
  2296.     {
  2297.       register struct file_entry *entry = &file_table[i];
  2298.       read_file_symbols (entry);
  2299.     }
  2300.  
  2301.   if (trace_files) fprintf (stderr, "\n");
  2302. }
  2303.  
  2304. /* If ENTRY is a rel file, read its symbol and string sections into core.
  2305.    If it is a library, search it and load the appropriate members
  2306.    (which means calling this function recursively on those members).  */
  2307.  
  2308. void
  2309. read_file_symbols (entry)
  2310.      register struct file_entry *entry;
  2311. {
  2312.   register int desc;
  2313.  
  2314.   desc = file_open (entry);
  2315.  
  2316.   if (!entry->file_type)
  2317.     deduce_file_type (desc, entry);
  2318.  
  2319.   if (entry->file_type == IS_ARCHIVE)
  2320.     {
  2321.       entry->library_flag = 1;
  2322.       search_library (desc, entry);
  2323.     }
  2324.   else
  2325.     {
  2326.       read_entry_symbols (desc, entry);
  2327.       entry->strings = (char *) alloca (entry->strs_size);
  2328.       read_entry_strings (desc, entry);
  2329.       enter_file_symbols (entry);
  2330.       entry->strings = 0;
  2331.     }
  2332.  
  2333.   file_close ();
  2334. }
  2335.  
  2336. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  2337.  
  2338. void
  2339. enter_file_symbols (entry)
  2340.      struct file_entry *entry;
  2341. {
  2342.   register struct nlist
  2343.     *p,
  2344.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2345.  
  2346.   if (trace_files) prline_file_name (entry, stderr);
  2347.  
  2348.   for (p = entry->symbols; p < end; p++)
  2349.     {
  2350.       if (p->n_type == (N_SETV | N_EXT)) continue;
  2351.       if (set_element_prefixes
  2352.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  2353.     p->n_type += (N_SETA - N_ABS);
  2354.  
  2355.       if (SET_ELEMENT_P (p->n_type))
  2356.     {
  2357.       set_symbol_count++;
  2358.       if (output_style != OUTPUT_RELOCATABLE)
  2359.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2360.     }
  2361.       else if (p->n_type == N_WARNING)
  2362.     {
  2363.       char *name = p->n_un.n_strx + entry->strings;
  2364.  
  2365.       /* Grab the next entry.  */
  2366.       p++;
  2367.       if (p->n_type != (N_UNDF | N_EXT))
  2368.         {
  2369.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  2370.                progname, entry->filename);
  2371.           make_executable = 0;
  2372.           p--;        /* Process normally.  */
  2373.         }
  2374.       else
  2375.         {
  2376.           symbol *sp;
  2377.           char *sname = p->n_un.n_strx + entry->strings;
  2378.           /* Deal with the warning symbol.  */
  2379.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2380.           sp = getsym (sname);
  2381.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  2382.           strcpy (sp->warning, name);
  2383.           warning_count++;
  2384.         }
  2385.     }
  2386.       else if (p->n_type & N_EXT)
  2387.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2388.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  2389.     {
  2390.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  2391.         non_L_local_sym_count++;
  2392.       local_sym_count++;
  2393.     }
  2394.       else debugger_sym_count++;
  2395.     }
  2396.  
  2397.    /* Count one for the local symbol that we generate,
  2398.       whose name is the file's name (usually) and whose address
  2399.       is the start of the file's text.  */
  2400.  
  2401.   local_sym_count++;
  2402.   non_L_local_sym_count++;
  2403. }
  2404.  
  2405. /* Enter one global symbol in the hash table.
  2406.    NLIST_P points to the `struct nlist' read from the file
  2407.    that describes the global symbol.  NAME is the symbol's name.
  2408.    ENTRY is the file entry for the file the symbol comes from.
  2409.  
  2410.    The `struct nlist' is modified by placing it on a chain of
  2411.    all such structs that refer to the same global symbol.
  2412.    This chain starts in the `refs' field of the symbol table entry
  2413.    and is chained through the `n_name'.  */
  2414.  
  2415. void
  2416. enter_global_ref (nlist_p, name, entry)
  2417.      register struct nlist *nlist_p;
  2418.      char *name;
  2419.      struct file_entry *entry;
  2420. {
  2421.   register symbol *sp = getsym (name);
  2422.   register int type = nlist_p->n_type;
  2423.   int oldref = sp->referenced;
  2424.   int olddef = sp->defined;
  2425.  
  2426.   nlist_p->n_un.n_name = (char *) sp->refs;
  2427.   sp->refs = nlist_p;
  2428.  
  2429.   sp->referenced = 1;
  2430.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  2431.     {
  2432.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  2433.     sp->defined = type;
  2434.  
  2435.       if (oldref && !olddef)
  2436.     /* It used to be undefined and we're defining it.  */
  2437.     undefined_global_sym_count--;
  2438.  
  2439.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2440.     {
  2441.       /* First definition and it's common.  */
  2442.       common_defined_global_count++;
  2443.       sp->max_common_size = nlist_p->n_value;
  2444.     }
  2445.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2446.     {
  2447.       /* It used to be common and we're defining it as
  2448.          something else.  */
  2449.       common_defined_global_count--;
  2450.       sp->max_common_size = 0;
  2451.     }
  2452.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2453.       && sp->max_common_size < nlist_p->n_value)
  2454.     /* It used to be common and this is a new common entry to
  2455.        which we need to pay attention.  */
  2456.     sp->max_common_size = nlist_p->n_value;
  2457.  
  2458.       /* Are we defining it as a set element?  */
  2459.       if (SET_ELEMENT_P (type)
  2460.       && (!olddef || (olddef && sp->max_common_size)))
  2461.     set_vector_count++;
  2462.       /* As an indirection?  */
  2463.       else if (type == (N_INDR | N_EXT))
  2464.     {
  2465.       /* Indirect symbols value should be modified to point
  2466.          a symbol being equivalenced to. */
  2467.       nlist_p->n_value
  2468. #ifndef NeXT
  2469.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2470.                      + entry->strings);
  2471. #else
  2472.         /* NeXT also has indirection but they do it weirdly. */
  2473.         = (unsigned int) getsym (nlist_p->n_value + entry->strings);
  2474. #endif
  2475.       if ((symbol *) nlist_p->n_value == sp)
  2476.         {
  2477.           /* Somebody redefined a symbol to be itself.  */
  2478.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2479.                entry->filename, name);
  2480.           /* Rewrite this symbol as being a global text symbol
  2481.          with value 0.  */
  2482.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2483.           nlist_p->n_value = 0;
  2484.           /* Don't make the output executable.  */
  2485.           make_executable = 0;
  2486.         }
  2487.       else
  2488.         global_indirect_count++;
  2489.     }
  2490.     }
  2491.   else
  2492.     if (!oldref)
  2493. #ifndef DOLLAR_KLUDGE
  2494.       undefined_global_sym_count++;
  2495. #else
  2496.       {
  2497.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2498.       {
  2499.         /* This is an (ISI?) $-conditional; skip it */
  2500.         sp->referenced = 0;
  2501.         if (sp->trace)
  2502.           {
  2503.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2504.         print_file_name (entry, stderr);
  2505.         fprintf (stderr, "\n");
  2506.           }
  2507.         return;
  2508.       }
  2509.     else
  2510.       undefined_global_sym_count++;
  2511.       }
  2512. #endif
  2513.  
  2514.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2515.     text_start = nlist_p->n_value;
  2516.  
  2517.   if (sp->trace)
  2518.     {
  2519.       register char *reftype;
  2520.       switch (type & ~N_EXT)
  2521.     {
  2522.     case N_UNDF:
  2523.       if (nlist_p->n_value)
  2524.         reftype = "defined as common";
  2525.       else reftype = "referenced";
  2526.       break;
  2527.  
  2528.     case N_ABS:
  2529.       reftype = "defined as absolute";
  2530.       break;
  2531.  
  2532.     case N_TEXT:
  2533.       reftype = "defined in text section";
  2534.       break;
  2535.  
  2536.     case N_DATA:
  2537.       reftype = "defined in data section";
  2538.       break;
  2539.  
  2540.     case N_BSS:
  2541.       reftype = "defined in BSS section";
  2542.       break;
  2543.  
  2544.     case N_SETT:
  2545.       reftype = "is a text set element";
  2546.       break;
  2547.  
  2548.     case N_SETD:
  2549.       reftype = "is a data set element";
  2550.       break;
  2551.  
  2552.     case N_SETB:
  2553.       reftype = "is a BSS set element";
  2554.       break;
  2555.  
  2556.     case N_SETA:
  2557.       reftype = "is an absolute set element";
  2558.       break;
  2559.  
  2560.     case N_SETV:
  2561.       reftype = "defined in data section as vector";
  2562.       break;
  2563.  
  2564.     case N_INDR:
  2565.       reftype = (char *) alloca (23 + strlen (((symbol *) nlist_p->n_value)->name));
  2566.       sprintf (reftype, "defined equivalent to %s",
  2567.            ((symbol *) nlist_p->n_value)->name);
  2568.       break;
  2569.  
  2570. #ifdef sequent
  2571.     case N_SHUNDF:
  2572.       reftype = "shared undf";
  2573.       break;
  2574.  
  2575. /* These conflict with cases above.
  2576.     case N_SHDATA:
  2577.       reftype = "shared data";
  2578.       break;
  2579.  
  2580.     case N_SHBSS:
  2581.       reftype = "shared BSS";
  2582.       break;
  2583. */
  2584. #endif
  2585.  
  2586.     default:
  2587.       reftype = "I don't know this type";
  2588.       break;
  2589.     }
  2590.  
  2591.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2592.       print_file_name (entry, stderr);
  2593.       fprintf (stderr, "\n");
  2594.     }
  2595. }
  2596.  
  2597. /* This return 0 if the given file entry's symbol table does *not*
  2598.    contain the nlist point entry, and it returns the files entry
  2599.    pointer (cast to unsigned long) if it does. */
  2600.  
  2601. unsigned long
  2602. contains_symbol (entry, n_ptr)
  2603.      struct file_entry *entry;
  2604.      register struct nlist *n_ptr;
  2605. {
  2606.   if (n_ptr >= entry->symbols &&
  2607.       n_ptr < (entry->symbols
  2608.            + (entry->syms_size / sizeof (struct nlist))))
  2609.     return (unsigned long) entry;
  2610.   return 0;
  2611. }
  2612.  
  2613.  
  2614. /* Searching libraries */
  2615.  
  2616. struct file_entry *decode_library_subfile ();
  2617. void linear_library (), symdef_library ();
  2618.  
  2619. /* Search the library ENTRY, already open on descriptor DESC.
  2620.    This means deciding which library members to load,
  2621.    making a chain of `struct file_entry' for those members,
  2622.    and entering their global symbols in the hash table.  */
  2623.  
  2624. void
  2625. search_library (desc, entry)
  2626.      int desc;
  2627.      struct file_entry *entry;
  2628. {
  2629.   int member_length;
  2630.   register char *name;
  2631.   register struct file_entry *subentry;
  2632.  
  2633.   if (!undefined_global_sym_count) return;
  2634.  
  2635.   /* Examine its first member, which starts SARMAG bytes in.  */
  2636.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2637.   if (!subentry) return;
  2638.  
  2639.   name = subentry->filename;
  2640.   free (subentry);
  2641.  
  2642.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2643.  
  2644.   if (!strcmp (name, "__.SYMDEF"))
  2645.     symdef_library (desc, entry, member_length);
  2646.   else
  2647.     linear_library (desc, entry);
  2648. }
  2649.  
  2650. /* Construct and return a file_entry for a library member.
  2651.    The library's file_entry is library_entry, and the library is open on DESC.
  2652.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2653.    We store the length of the member into *LENGTH_LOC.  */
  2654.  
  2655. struct file_entry *
  2656. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2657.      int desc;
  2658.      struct file_entry *library_entry;
  2659.      int subfile_offset;
  2660.      int *length_loc;
  2661. {
  2662.   int bytes_read;
  2663.   register int namelen;
  2664.   int member_length;
  2665.   register char *name;
  2666.   struct ar_hdr hdr1;
  2667.   register struct file_entry *subentry;
  2668.  
  2669.   lseek (desc, subfile_offset, 0);
  2670.  
  2671.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2672.   if (!bytes_read)
  2673.     return 0;        /* end of archive */
  2674.  
  2675.   if (sizeof hdr1 != bytes_read)
  2676.     fatal_with_file ("malformed library archive ", library_entry);
  2677.  
  2678.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2679.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2680.  
  2681.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2682.   bzero (subentry, sizeof (struct file_entry));
  2683.  
  2684.   for (namelen = 0;
  2685.        namelen < sizeof hdr1.ar_name
  2686.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2687.        && hdr1.ar_name[namelen] != '/';
  2688.        namelen++);
  2689.  
  2690.   name = (char *) xmalloc (namelen+1);
  2691.   strncpy (name, hdr1.ar_name, namelen);
  2692.   name[namelen] = 0;
  2693.  
  2694.   subentry->filename = name;
  2695.   subentry->local_sym_name = name;
  2696.   subentry->symbols = 0;
  2697.   subentry->strings = 0;
  2698.   subentry->subfiles = 0;
  2699.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2700.   subentry->superfile = library_entry;
  2701.   subentry->library_flag = 0;
  2702.   subentry->header_read_flag = 0;
  2703.   subentry->just_syms_flag = 0;
  2704.   subentry->chain = 0;
  2705.   subentry->total_size = member_length;
  2706.  
  2707.   (*length_loc) = member_length;
  2708.  
  2709.   return subentry;
  2710. }
  2711.  
  2712. int subfile_wanted_p ();
  2713.  
  2714. /* Search a library that has a __.SYMDEF member.
  2715.    DESC is a descriptor on which the library is open.
  2716.      The file pointer is assumed to point at the __.SYMDEF data.
  2717.    ENTRY is the library's file_entry.
  2718.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2719.  
  2720. void
  2721. symdef_library (desc, entry, member_length)
  2722.      int desc;
  2723.      struct file_entry *entry;
  2724.      int member_length;
  2725. {
  2726.   int *symdef_data = (int *) xmalloc (member_length);
  2727.   register struct symdef *symdef_base;
  2728.   char *sym_name_base;
  2729.   int number_of_symdefs;
  2730.   int length_of_strings;
  2731.   int not_finished;
  2732.   int bytes_read;
  2733.   register int i;
  2734.   struct file_entry *prev = 0;
  2735.   int prev_offset = 0;
  2736.  
  2737.   bytes_read = read (desc, symdef_data, member_length);
  2738.   if (bytes_read != member_length)
  2739.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2740. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2741.   fix_byte_order(symdef_data, sizeof(*symdef_data));
  2742. #endif
  2743.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2744.   if (number_of_symdefs < 0 ||
  2745.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2746.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2747.  
  2748.   symdef_base = (struct symdef *) (symdef_data + 1);
  2749. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2750.   for (i = 0; i < number_of_symdefs; ++i)
  2751.     {
  2752.       fix_byte_order(&symdef_base[i].symbol_name_string_index, sizeof(int));
  2753.       fix_byte_order(&symdef_base[i].library_member_offset, sizeof(int));
  2754.     }
  2755.   fix_byte_order(symdef_base + number_of_symdefs, sizeof(int));
  2756. #endif
  2757.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2758.  
  2759.   if (length_of_strings < 0
  2760.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2761.       + 2 * sizeof (int) != member_length)
  2762.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2763.  
  2764.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2765.  
  2766.   /* Check all the string indexes for validity.  */
  2767.  
  2768.   for (i = 0; i < number_of_symdefs; i++)
  2769.     {
  2770.       register int index = symdef_base[i].symbol_name_string_index;
  2771.       if (index < 0 || index >= length_of_strings
  2772.       || (index && *(sym_name_base + index - 1)))
  2773.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2774.     }
  2775.  
  2776.   /* Search the symdef data for members to load.
  2777.      Do this until one whole pass finds nothing to load.  */
  2778.  
  2779.   not_finished = 1;
  2780.   while (not_finished)
  2781.     {
  2782.       not_finished = 0;
  2783.  
  2784.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2785.      Load the library members that contain such symbols.  */
  2786.  
  2787.       for (i = 0;
  2788.        (i < number_of_symdefs
  2789.         && (undefined_global_sym_count || common_defined_global_count));
  2790.        i++)
  2791.     if (symdef_base[i].symbol_name_string_index >= 0)
  2792.       {
  2793.         register symbol *sp;
  2794.  
  2795.         sp = getsym_soft (sym_name_base
  2796.                   + symdef_base[i].symbol_name_string_index);
  2797.  
  2798.         /* If we find a symbol that appears to be needed, think carefully
  2799.            about the archive member that the symbol is in.  */
  2800.  
  2801.         if (sp && ((sp->referenced && !sp->defined)
  2802.                || (sp->defined && sp->max_common_size)))
  2803.           {
  2804.         int junk;
  2805.         register int j;
  2806.         register int offset = symdef_base[i].library_member_offset;
  2807.         struct file_entry *subentry;
  2808.  
  2809.         /* Don't think carefully about any archive member
  2810.            more than once in a given pass.  */
  2811.  
  2812.         if (prev_offset == offset)
  2813.           continue;
  2814.         prev_offset = offset;
  2815.  
  2816.         /* Read the symbol table of the archive member.  */
  2817.  
  2818.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2819.         if (subentry == 0)
  2820.           fatal ("invalid offset for %s in symbol table of %s",
  2821.              sym_name_base
  2822.              + symdef_base[i].symbol_name_string_index,
  2823.              entry->filename);
  2824.         read_entry_symbols (desc, subentry);
  2825.         subentry->strings = xmalloc (subentry->strs_size);
  2826.         read_entry_strings (desc, subentry);
  2827.  
  2828.         /* Now scan the symbol table and decide whether to load.  */
  2829.  
  2830.         if (!subfile_wanted_p (subentry))
  2831.           {
  2832.             free (subentry->symbols);
  2833.             free (subentry->strings);
  2834.             free (subentry);
  2835.           }
  2836.         else
  2837.           {
  2838.             /* This member is needed; load it.
  2839.                Since we are loading something on this pass,
  2840.                we must make another pass through the symdef data.  */
  2841.  
  2842.             not_finished = 1;
  2843.  
  2844.             enter_file_symbols (subentry);
  2845.  
  2846.             if (prev)
  2847.               prev->chain = subentry;
  2848.             else entry->subfiles = subentry;
  2849.             prev = subentry;
  2850.  
  2851.             /* Clear out this member's symbols from the symdef data
  2852.                so that following passes won't waste time on them.  */
  2853.  
  2854.             for (j = 0; j < number_of_symdefs; j++)
  2855.               {
  2856.             if (symdef_base[j].library_member_offset == offset)
  2857.               symdef_base[j].symbol_name_string_index = -1;
  2858.               }
  2859.  
  2860.             /* We'll read the strings again if we need them again.  */
  2861.             free (subentry->strings);
  2862.             subentry->strings = 0;
  2863.           }
  2864.           }
  2865.       }
  2866.     }
  2867.  
  2868.   free (symdef_data);
  2869. }
  2870.  
  2871.  
  2872. /* Handle a subentry for a file with no __.SYMDEF. */
  2873.  
  2874. process_subentry (desc, subentry, entry, prev_addr)
  2875.      int desc;
  2876.      register struct file_entry *subentry;
  2877.      struct file_entry **prev_addr, *entry;
  2878. {
  2879.   read_entry_symbols (desc, subentry);
  2880.   subentry->strings = (char *) alloca (subentry->strs_size);
  2881.   read_entry_strings (desc, subentry);
  2882.  
  2883.   if (!subfile_wanted_p (subentry))
  2884.     {
  2885.       free (subentry->symbols);
  2886.       free (subentry);
  2887.     }
  2888.   else
  2889.     {
  2890.       enter_file_symbols (subentry);
  2891.  
  2892.       if (*prev_addr)
  2893.     (*prev_addr)->chain = subentry;
  2894.       else
  2895.     entry->subfiles = subentry;
  2896.       *prev_addr = subentry;
  2897.       subentry->strings = 0; /* Since space will dissapear on return */
  2898.     }
  2899. }
  2900.  
  2901. /* Search a library that has no __.SYMDEF.
  2902.    ENTRY is the library's file_entry.
  2903.    DESC is the descriptor it is open on.  */
  2904.  
  2905. void
  2906. linear_library (desc, entry)
  2907.      int desc;
  2908.      struct file_entry *entry;
  2909. {
  2910.   struct file_entry *prev = 0;
  2911.   register int this_subfile_offset = SARMAG;
  2912.  
  2913.   while (undefined_global_sym_count || common_defined_global_count)
  2914.     {
  2915.       int member_length;
  2916.       register struct file_entry *subentry;
  2917.  
  2918.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2919.                      &member_length);
  2920.       if (!subentry) return;
  2921.  
  2922.       process_subentry (desc, subentry, entry, &prev);
  2923.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2924.       if (this_subfile_offset & 1) this_subfile_offset++;
  2925.     }
  2926. }
  2927.  
  2928. /* ENTRY is an entry for a library member.
  2929.    Its symbols have been read into core, but not entered.
  2930.    Return nonzero if we ought to load this member.  */
  2931.  
  2932. int
  2933. subfile_wanted_p (entry)
  2934.      struct file_entry *entry;
  2935. {
  2936.   register struct nlist *p;
  2937.   register struct nlist *end
  2938.     = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2939. #ifdef DOLLAR_KLUDGE
  2940.   register int dollar_cond = 0;
  2941. #endif
  2942.  
  2943.   for (p = entry->symbols; p < end; p++)
  2944.     {
  2945.       register int type = p->n_type;
  2946.       register char *name = p->n_un.n_strx + entry->strings;
  2947.  
  2948.       /* If the symbol has an interesting definition, we could
  2949.      potentially want it.  */
  2950.       if (type & N_EXT
  2951.       && (type != (N_UNDF | N_EXT) || p->n_value
  2952.  
  2953. #ifdef DOLLAR_KLUDGE
  2954.            || name[1] == '$'
  2955. #endif
  2956.           )
  2957.       && !SET_ELEMENT_P (type)
  2958.       && !set_element_prefixed_p (name))
  2959.     {
  2960.       register symbol *sp = getsym_soft (name);
  2961.  
  2962. #ifdef DOLLAR_KLUDGE
  2963.       if (name[1] == '$')
  2964.         {
  2965.           sp = getsym_soft (&name[2]);
  2966.           dollar_cond = 1;
  2967.           if (!sp) continue;
  2968.           if (sp->referenced)
  2969.         {
  2970.           if (write_map)
  2971.             {
  2972.               print_file_name (entry, stdout);
  2973.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2974.             }
  2975.           return 1;
  2976.         }
  2977.           continue;
  2978.         }
  2979. #endif
  2980.  
  2981.       /* If this symbol has not been hashed, we can't be looking for it. */
  2982.  
  2983.       if (!sp) continue;
  2984.  
  2985.       if ((sp->referenced && !sp->defined)
  2986.           /* NB.  This needs to be changed so that, e.g., "int pipe;" won't import
  2987.          pipe() from the library.  But the bug fix kingdon made was wrong.  */
  2988.           || (sp->defined && sp->max_common_size))
  2989.         {
  2990.           /* This is a symbol we are looking for.  It is either
  2991.              not yet defined or defined as a common.  */
  2992. #ifdef DOLLAR_KLUDGE
  2993.           if (dollar_cond) continue;
  2994. #endif
  2995.           if (type == (N_UNDF | N_EXT))
  2996.         {
  2997.           /* Symbol being defined as common.
  2998.              Remember this, but don't load subfile just for this.  */
  2999.  
  3000.           /* If it didn't used to be common, up the count of
  3001.              common symbols.  */
  3002.           if (!sp->max_common_size)
  3003.             common_defined_global_count++;
  3004.  
  3005.           if (sp->max_common_size < p->n_value)
  3006.             sp->max_common_size = p->n_value;
  3007.           if (!sp->defined)
  3008.             undefined_global_sym_count--;
  3009.           sp->defined = 1;
  3010.           continue;
  3011.         }
  3012.  
  3013.           if (write_map)
  3014.         {
  3015.           print_file_name (entry, stdout);
  3016.           fprintf (stdout, " needed due to %s\n", sp->name);
  3017.         }
  3018.           return 1;
  3019.         }
  3020.     }
  3021.     }
  3022.  
  3023.   return 0;
  3024. }
  3025.  
  3026. void consider_file_section_lengths (), relocate_file_addresses ();
  3027.  
  3028. /* Having entered all the global symbols and found the sizes of sections
  3029.    of all files to be linked, make all appropriate deductions from this data.
  3030.  
  3031.    We propagate global symbol values from definitions to references.
  3032.    We compute the layout of the output file and where each input file's
  3033.    contents fit into it.  */
  3034.  
  3035. void
  3036. digest_symbols ()
  3037. {
  3038.   register int i;
  3039.   int setv_fill_count;
  3040.  
  3041.   if (trace_files)
  3042.     fprintf (stderr, "Digesting symbol information:\n\n");
  3043.  
  3044.   /* Initialize the text_start address; this depends on the output file formats.  */
  3045.  
  3046.   initialize_text_start ();
  3047.  
  3048.   text_size = text_header_size;
  3049.  
  3050.   /* Compute total size of sections */
  3051.  
  3052.   each_file (consider_file_section_lengths, 0);
  3053.  
  3054.   /* If necessary, pad text section to full page in the file.
  3055.      Include the padding in the text segment size.  */
  3056.  
  3057.   if (output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  3058.     {
  3059.       text_pad = ((text_size + page_size - 1) & (- page_size)) - text_size;
  3060.       text_size += text_pad;
  3061.     }
  3062.  
  3063.   /* Now that the text_size is known, initialize the data start address;
  3064.      this depends on text_size as well as the output file format.  */
  3065.  
  3066.   initialize_data_start ();
  3067.  
  3068.   /* Make sure bss starts out aligned as much as anyone can want.  */
  3069.   {
  3070.     int new_data_size = (data_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3071.  
  3072.     data_pad += new_data_size - data_size;
  3073.     data_size = new_data_size;
  3074.   }
  3075.  
  3076.   /* Set up the set element vector */
  3077.  
  3078.   if (output_style != OUTPUT_RELOCATABLE)
  3079.     {
  3080.       /* The set sector size is the number of set elements + a word
  3081.          for each symbol for the length word at the beginning of the
  3082.      vector, plus a word for each symbol for a zero at the end of
  3083.      the vector (for incremental linking).  */
  3084.       set_sect_size
  3085.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  3086.       set_sect_start = data_start + data_size;
  3087.       data_size += set_sect_size;
  3088.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  3089.       setv_fill_count = 0;
  3090.     }
  3091.  
  3092.   /* Compute start addresses of each file's sections and symbols.  */
  3093.  
  3094.   each_full_file (relocate_file_addresses, 0);
  3095.  
  3096.   /* Now, for each symbol, verify that it is defined globally at most once.
  3097.      Put the global value into the symbol entry.
  3098.      Common symbols are allocated here, in the BSS section.
  3099.      Each defined symbol is given a '->defined' field
  3100.       which is the correct N_ code for its definition,
  3101.       except in the case of common symbols with -r.
  3102.      Then make all the references point at the symbol entry
  3103.      instead of being chained together. */
  3104.  
  3105.   defined_global_sym_count = 0;
  3106.  
  3107.   for (i = 0; i < TABSIZE; i++)
  3108.     {
  3109.       register symbol *sp;
  3110.       for (sp = symtab[i]; sp; sp = sp->link)
  3111.     {
  3112.       /* For each symbol */
  3113.       register struct nlist *p, *next;
  3114.       int defs = 0, com = sp->max_common_size;
  3115.       struct nlist *first_definition;
  3116.       for (p = sp->refs; p; p = next)
  3117.         {
  3118.           register int type = p->n_type;
  3119.  
  3120.           if (SET_ELEMENT_P (type))
  3121.         {
  3122.           if (output_style == OUTPUT_RELOCATABLE)
  3123.             fatal ("internal: global ref to set element with -r");
  3124.           if (!defs++)
  3125.             {
  3126.               sp->value = set_sect_start
  3127.             + setv_fill_count++ * sizeof (unsigned long);
  3128.               sp->defined = N_SETV | N_EXT;
  3129.               first_definition = p;
  3130.             }
  3131.           else if ((sp->defined & ~N_EXT) != N_SETV)
  3132.             {
  3133.               sp->multiply_defined = 1;
  3134.               multiple_def_count++;
  3135.             }
  3136.           set_vectors[setv_fill_count++] = p->n_value;
  3137.         }
  3138.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  3139.         {
  3140.           /* non-common definition */
  3141.           if (defs++ && sp->value != p->n_value)
  3142.             {
  3143.               sp->multiply_defined = 1;
  3144.               multiple_def_count++;
  3145.             }
  3146.           sp->value = p->n_value;
  3147.           sp->defined = type;
  3148.           first_definition = p;
  3149.         }
  3150.           next = (struct nlist *) p->n_un.n_name;
  3151.           p->n_un.n_name = (char *) sp;
  3152.         }
  3153.       /* Allocate as common if defined as common and not defined for real */
  3154.       if (com && !defs)
  3155.         {
  3156.           if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
  3157.         {
  3158.           int align = sizeof (int);
  3159.  
  3160.           /* Round up to nearest sizeof (int).  I don't know
  3161.              whether this is necessary or not (given that
  3162.              alignment is taken care of later), but it's
  3163.              traditional, so I'll leave it in.  Note that if
  3164.              this size alignment is ever removed, ALIGN above
  3165.              will have to be initialized to 1 instead of
  3166.              sizeof (int).  */
  3167.  
  3168.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  3169.  
  3170.           while (!(com & align))
  3171.             align <<= 1;
  3172.  
  3173.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  3174.  
  3175.           bss_size = ((((bss_size + data_size + data_start)
  3176.                   + (align - 1)) & (- align))
  3177.                   - data_size - data_start);
  3178.  
  3179.           sp->value = data_start + data_size + bss_size;
  3180.           sp->defined = N_BSS | N_EXT;
  3181.           bss_size += com;
  3182.           if (write_map)
  3183.             printf ("Allocating common %s: %x at %x\n",
  3184.                 sp->name, com, sp->value);
  3185.         }
  3186.           else
  3187.         {
  3188.           sp->defined = 0;
  3189.           undefined_global_sym_count++;
  3190.         }
  3191.         }
  3192.       /* Set length word at front of vector and zero byte at end.
  3193.          Reverse the vector itself to put it in file order.  */
  3194.       if ((sp->defined & ~N_EXT) == N_SETV)
  3195.         {
  3196.           unsigned long length_word_index
  3197.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  3198.           unsigned long i, tmp;
  3199.  
  3200.           set_vectors[length_word_index]
  3201.         = setv_fill_count - 1 - length_word_index;
  3202.  
  3203.           /* Reverse the vector.  */
  3204.           for (i = 1;
  3205.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  3206.            i++)
  3207.         {
  3208.           tmp = set_vectors[length_word_index + i];
  3209.           set_vectors[length_word_index + i]
  3210.             = set_vectors[setv_fill_count - i];
  3211.           set_vectors[setv_fill_count - i] = tmp;
  3212.         }
  3213.  
  3214.           set_vectors[setv_fill_count++] = 0;
  3215.         }
  3216.       if (sp->defined)
  3217.         defined_global_sym_count++;
  3218.     }
  3219.     }
  3220.  
  3221.   /* Make sure end of bss is aligned as much as anyone can want.  */
  3222.  
  3223.   bss_size = (bss_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3224.  
  3225.   /* Give values to _end and friends.  */
  3226.   {
  3227.     int end_value = data_start + data_size + bss_size;
  3228.     if (end_symbol)
  3229.       end_symbol->value = end_value;
  3230.     if (end_symbol_alt)
  3231.       end_symbol_alt->value = end_value;
  3232.   }
  3233.  
  3234.   {
  3235.     int etext_value = text_size + text_start;
  3236.     if (etext_symbol)
  3237.       etext_symbol->value = etext_value;
  3238.     if (etext_symbol_alt)
  3239.       etext_symbol_alt->value = etext_value;
  3240.   }
  3241.  
  3242.   {
  3243.     int edata_value = data_start + data_size;
  3244.     if (edata_symbol)
  3245.       edata_symbol->value = edata_value;
  3246.     if (edata_symbol_alt)
  3247.       edata_symbol_alt->value = edata_value;
  3248.   }
  3249.  
  3250.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  3251.  
  3252.   {
  3253.     /* The amount of data_pad that we are computing now.  This is the
  3254.        part which overlaps with bss.  What was computed previously
  3255.        goes before bss.  */
  3256.     int data_pad_additional = 0;
  3257.     
  3258.     if (specified_data_size && specified_data_size > data_size)
  3259.       data_pad_additional = specified_data_size - data_size;
  3260.  
  3261.     if (output_style == OUTPUT_DEMAND_PAGED)
  3262.       data_pad_additional =
  3263.     ((data_pad_additional + data_size + page_size - 1) & (- page_size)) - data_size;
  3264.  
  3265.     bss_size -= data_pad_additional;
  3266.     if (bss_size < 0) bss_size = 0;
  3267.  
  3268.     data_size += data_pad_additional;
  3269.  
  3270.     data_pad += data_pad_additional;
  3271.   }
  3272. }
  3273.  
  3274. /* Accumulate the section sizes of input file ENTRY
  3275.    into the section sizes of the output file.  */
  3276.  
  3277. void
  3278. consider_file_section_lengths (entry)
  3279.      register struct file_entry *entry;
  3280. {
  3281.   if (entry->just_syms_flag)
  3282.     return;
  3283.  
  3284.   entry->text_start_address = text_size;
  3285.   /* If there were any vectors, we need to chop them off */
  3286.   text_size += entry->text_size;
  3287.   entry->data_start_address = data_size;
  3288.   data_size += entry->data_size;
  3289.   entry->bss_start_address = bss_size;
  3290.   bss_size += entry->bss_size;
  3291.  
  3292.   text_reloc_size += entry->text_reloc_size;
  3293.   data_reloc_size += entry->data_reloc_size;
  3294. }
  3295.  
  3296. /* Determine where the sections of ENTRY go into the output file,
  3297.    whose total section sizes are already known.
  3298.    Also relocate the addresses of the file's local and debugger symbols.  */
  3299.  
  3300. void
  3301. relocate_file_addresses (entry)
  3302.      register struct file_entry *entry;
  3303. {
  3304.   entry->text_start_address += text_start;
  3305.  
  3306.   /* Note that `data_start' and `data_size' have not yet been adjusted
  3307.      for the portion of data_pad which overlaps with bss.  If they had
  3308.      been, we would get the wrong results here.  */
  3309.   entry->data_start_address += data_start;
  3310.   entry->bss_start_address += data_start + data_size;
  3311.  
  3312.   {
  3313.     register struct nlist *p;
  3314.     register struct nlist *end
  3315.       = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3316.  
  3317.     for (p = entry->symbols; p < end; p++)
  3318.       {
  3319.     /* If this belongs to a section, update it by the section's start address */
  3320.     register int type = p->n_type & ~N_EXT;
  3321.  
  3322.     switch (type)
  3323.       {
  3324.       case N_TEXT:
  3325.       case N_SETT:
  3326.         p->n_value += entry->text_start_address - entry->orig_text_address;
  3327.         break;
  3328.       case N_DATA:
  3329.       case N_SETV:
  3330.       case N_SETD:
  3331.         /* Data segment symbol.  Subtract the address of the
  3332.            data segment in the input file, and add the address
  3333.            of this input file's data segment in the output file.  */
  3334.         p->n_value +=
  3335.           entry->data_start_address - entry->orig_data_address;
  3336.         break;
  3337.       case N_BSS:
  3338.       case N_SETB:
  3339.         /* likewise for symbols with value in BSS.  */
  3340.         p->n_value += entry->bss_start_address - entry->orig_bss_address;
  3341.         break;
  3342.       }
  3343.       }
  3344.   }
  3345. }
  3346.  
  3347. void describe_file_sections (), list_file_locals ();
  3348.  
  3349. /* Print a complete or partial map of the output file.  */
  3350.  
  3351. void
  3352. print_symbols (outfile)
  3353.      FILE *outfile;
  3354. {
  3355.   register int i;
  3356.  
  3357.   fprintf (outfile, "\nFiles:\n\n");
  3358.  
  3359.   each_file (describe_file_sections, outfile);
  3360.  
  3361.   fprintf (outfile, "\nGlobal symbols:\n\n");
  3362.  
  3363.   for (i = 0; i < TABSIZE; i++)
  3364.     {
  3365.       register symbol *sp;
  3366.       for (sp = symtab[i]; sp; sp = sp->link)
  3367.     {
  3368.       if (sp->defined == 1)
  3369.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  3370.       if (sp->defined)
  3371.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  3372.       else if (sp->referenced)
  3373.         fprintf (outfile, "  %s: undefined\n", sp->name);
  3374.     }
  3375.     }
  3376.  
  3377.   each_file (list_file_locals, outfile);
  3378. }
  3379.  
  3380. void
  3381. describe_file_sections (entry, outfile)
  3382.      struct file_entry *entry;
  3383.      FILE *outfile;
  3384. {
  3385.   fprintf (outfile, "  ");
  3386.   print_file_name (entry, outfile);
  3387.   if (entry->just_syms_flag)
  3388.     fprintf (outfile, " symbols only\n", 0);
  3389.   else
  3390.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  3391.          entry->text_start_address, entry->text_size,
  3392.          entry->data_start_address, entry->data_size,
  3393.          entry->bss_start_address, entry->bss_size);
  3394. }
  3395.  
  3396. void
  3397. list_file_locals (entry, outfile)
  3398.      struct file_entry *entry;
  3399.      FILE *outfile;
  3400. {
  3401.   register struct nlist
  3402.     *p,
  3403.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3404.  
  3405.   entry->strings = (char *) alloca (entry->strs_size);
  3406.   read_entry_strings (file_open (entry), entry);
  3407.  
  3408.   fprintf (outfile, "\nLocal symbols of ");
  3409.   print_file_name (entry, outfile);
  3410.   fprintf (outfile, ":\n\n");
  3411.  
  3412.   for (p = entry->symbols; p < end; p++)
  3413.     /* If this is a definition,
  3414.        update it if necessary by this file's start address.  */
  3415.     if (!(p->n_type & (N_STAB | N_EXT)))
  3416.       fprintf (outfile, "  %s: 0x%x\n",
  3417.            entry->strings + p->n_un.n_strx, p->n_value);
  3418.  
  3419.   entry->strings = 0;        /* All done with them.  */
  3420. }
  3421.  
  3422.  
  3423. /* Static vars for do_warnings and subroutines of it */
  3424. int list_unresolved_refs;    /* List unresolved refs */
  3425. int list_warning_symbols;    /* List warning syms */
  3426. int list_multiple_defs;        /* List multiple definitions */
  3427.  
  3428. /*
  3429.  * Structure for communication between do_file_warnings and it's
  3430.  * helper routines.  Will in practice be an array of three of these:
  3431.  * 0) Current line, 1) Next line, 2) Source file info.
  3432.  */
  3433. struct line_debug_entry
  3434. {
  3435.   int line;
  3436.   char *filename;
  3437.   struct nlist *sym;
  3438. };
  3439.  
  3440. void qsort ();
  3441. /*
  3442.  * Helper routines for do_file_warnings.
  3443.  */
  3444.  
  3445. /* Return an integer less than, equal to, or greater than 0 as per the
  3446.    relation between the two relocation entries.  Used by qsort.  */
  3447.  
  3448. int
  3449. relocation_entries_relation (rel1, rel2)
  3450.      struct relocation_info *rel1, *rel2;
  3451. {
  3452.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3453. }
  3454.  
  3455. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  3456.    determines the type of the debugging symbol to look for (DSLINE or
  3457.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  3458.    the file.  It assumes that state_pointer[1] is valid; ie
  3459.    that it.sym points into some entry in the symbol table.  If
  3460.    state_pointer[1].sym == 0, this routine should not be called.  */
  3461.  
  3462. int
  3463. next_debug_entry (use_data_symbols, state_pointer)
  3464.      register int use_data_symbols;
  3465.      /* Next must be passed by reference! */
  3466.      struct line_debug_entry state_pointer[3];
  3467. {
  3468.   register struct line_debug_entry
  3469.     *current = state_pointer,
  3470.     *next = state_pointer + 1,
  3471.     /* Used to store source file */
  3472.     *source = state_pointer + 2;
  3473.   struct file_entry *entry = (struct file_entry *) source->sym;
  3474.  
  3475.   current->sym = next->sym;
  3476.   current->line = next->line;
  3477.   current->filename = next->filename;
  3478.  
  3479.   while (++(next->sym) < (entry->symbols
  3480.               + entry->syms_size/sizeof (struct nlist)))
  3481.     {
  3482.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  3483.        * may look negative...therefore, must mask to low bits
  3484.        */
  3485.       switch (next->sym->n_type & 0xff)
  3486.     {
  3487.     case N_SLINE:
  3488.       if (use_data_symbols) continue;
  3489.       next->line = next->sym->n_desc;
  3490.       return 1;
  3491.     case N_DSLINE:
  3492.       if (!use_data_symbols) continue;
  3493.       next->line = next->sym->n_desc;
  3494.       return 1;
  3495. #ifdef HAVE_SUN_STABS
  3496.     case N_EINCL:
  3497.       next->filename = source->filename;
  3498.       continue;
  3499. #endif
  3500.     case N_SO:
  3501.       source->filename = next->sym->n_un.n_strx + entry->strings;
  3502.       source->line++;
  3503. #ifdef HAVE_SUN_STABS
  3504.     case N_BINCL:
  3505. #endif
  3506.     case N_SOL:
  3507.       next->filename
  3508.         = next->sym->n_un.n_strx + entry->strings;
  3509.     default:
  3510.       continue;
  3511.     }
  3512.     }
  3513.   next->sym = (struct nlist *) 0;
  3514.   return 0;
  3515. }
  3516.  
  3517. /* Create a structure to save the state of a scan through the debug
  3518.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  3519.    DSLINE's instead of SLINE's.  entry is the file entry which points
  3520.    at the symbols to use.  */
  3521.  
  3522. struct line_debug_entry *
  3523. init_debug_scan (use_data_symbols, entry)
  3524.      int use_data_symbols;
  3525.      struct file_entry *entry;
  3526. {
  3527.   struct line_debug_entry
  3528.     *state_pointer
  3529.       = (struct line_debug_entry *)
  3530.     xmalloc (3 * sizeof (struct line_debug_entry));
  3531.   register struct line_debug_entry
  3532.     *current = state_pointer,
  3533.     *next = state_pointer + 1,
  3534.     *source = state_pointer + 2; /* Used to store source file */
  3535.  
  3536.   struct nlist *tmp;
  3537.  
  3538.   for (tmp = entry->symbols;
  3539.        tmp < (entry->symbols
  3540.           + entry->syms_size/sizeof (struct nlist));
  3541.        tmp++)
  3542.     if (tmp->n_type == (int) N_SO)
  3543.       break;
  3544.  
  3545.   if (tmp >= (entry->symbols
  3546.           + entry->syms_size/sizeof (struct nlist)))
  3547.     {
  3548.       /* I believe this translates to "We lose" */
  3549.       current->filename = next->filename = entry->filename;
  3550.       current->line = next->line = -1;
  3551.       current->sym = next->sym = (struct nlist *) 0;
  3552.       return state_pointer;
  3553.     }
  3554.  
  3555.   next->line = source->line = 0;
  3556.   next->filename = source->filename
  3557.     = (tmp->n_un.n_strx + entry->strings);
  3558.   source->sym = (struct nlist *) entry;
  3559.   next->sym = tmp;
  3560.  
  3561.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3562.  
  3563.   if (!next->sym)        /* No line numbers for this section; */
  3564.                 /* setup output results as appropriate */
  3565.     {
  3566.       if (source->line)
  3567.     {
  3568.       current->filename = source->filename = entry->filename;
  3569.       current->line = -1;    /* Don't print lineno */
  3570.     }
  3571.       else
  3572.     {
  3573.       current->filename = source->filename;
  3574.       current->line = 0;
  3575.     }
  3576.       return state_pointer;
  3577.     }
  3578.  
  3579.  
  3580.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3581.  
  3582.   return state_pointer;
  3583. }
  3584.  
  3585. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  3586.    which describes the current location in the implied scan through
  3587.    the debug symbols within the file which ADDRESS is within, and
  3588.    returns the source line number which corresponds to ADDRESS.  */
  3589.  
  3590. int
  3591. address_to_line (address, state_pointer)
  3592.      unsigned long address;
  3593.      /* Next must be passed by reference! */
  3594.      struct line_debug_entry state_pointer[3];
  3595. {
  3596.   struct line_debug_entry
  3597.     *current = state_pointer,
  3598.     *next = state_pointer + 1;
  3599.   struct line_debug_entry *tmp_pointer;
  3600.  
  3601.   int use_data_symbols;
  3602.  
  3603.   if (next->sym)
  3604.     use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
  3605.   else
  3606.     return current->line;
  3607.  
  3608.   /* Go back to the beginning if we've already passed it.  */
  3609.   if (current->sym->n_value > address)
  3610.     {
  3611.       tmp_pointer = init_debug_scan (use_data_symbols,
  3612.                      (struct file_entry *)
  3613.                      ((state_pointer + 2)->sym));
  3614.       state_pointer[0] = tmp_pointer[0];
  3615.       state_pointer[1] = tmp_pointer[1];
  3616.       state_pointer[2] = tmp_pointer[2];
  3617.       free (tmp_pointer);
  3618.     }
  3619.  
  3620.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3621.   if (current->sym->n_value > address)
  3622.     return -1;
  3623.  
  3624.   while (next->sym
  3625.      && next->sym->n_value <= address
  3626.      && next_debug_entry (use_data_symbols, state_pointer))
  3627.     ;
  3628.   return current->line;
  3629. }
  3630.  
  3631.  
  3632. /* Macros for manipulating bitvectors.  */
  3633. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3634. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3635.  
  3636. /* This routine will scan through the relocation data of file ENTRY,
  3637.    printing out references to undefined symbols and references to
  3638.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3639.    is non-zero, it will scan the data relocation segment (and use
  3640.    N_DSLINE symbols to track line number); otherwise it will scan the
  3641.    text relocation segment.  Warnings will be printed on the output
  3642.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3643.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3644.    we scan the nlists themselves.  */
  3645.  
  3646. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3647.      struct file_entry *entry;
  3648.      int data_segment;
  3649.      FILE *outfile;
  3650.      unsigned char *nlist_bitvector;
  3651. {
  3652.   struct relocation_info
  3653.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3654.     *reloc;
  3655.   int reloc_size
  3656.     = ((data_segment ? entry->data_reloc_size : entry->text_reloc_size)
  3657.        / sizeof (struct relocation_info));
  3658.   int start_of_segment
  3659.     = (data_segment ? entry->data_start_address : entry->text_start_address);
  3660.   struct nlist *start_of_syms = entry->symbols;
  3661.   struct line_debug_entry *state_pointer
  3662.     = init_debug_scan (data_segment != 0, entry);
  3663.   register struct line_debug_entry *current = state_pointer;
  3664.   /* Assigned to generally static values; should not be written into.  */
  3665.   char *errfmt;
  3666.   /* Assigned to alloca'd values cand copied into; should be freed
  3667.      when done.  */
  3668.   char *errmsg;
  3669.   int invalidate_line_number;
  3670.  
  3671.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3672.      for one lousy error optimization. */
  3673.  
  3674.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3675.      relocation_entries_relation);
  3676.  
  3677.   for (reloc = reloc_start;
  3678.        reloc < (reloc_start + reloc_size);
  3679.        reloc++)
  3680.     {
  3681.       register struct nlist *s;
  3682.       register symbol *g;
  3683.  
  3684.       /* If the relocation isn't resolved through a symbol, continue */
  3685.       if (!RELOC_EXTERN_P(reloc))
  3686.     continue;
  3687.  
  3688.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3689.  
  3690.       /* Local symbols shouldn't ever be used by relocation info, so
  3691.      the next should be safe.
  3692.      This is, of course, wrong.  References to local BSS symbols can be
  3693.      the targets of relocation info, and they can (must) be
  3694.      resolved through symbols.  However, these must be defined properly,
  3695.      (the assembler would have caught it otherwise), so we can
  3696.      ignore these cases.  */
  3697.       if (!(s->n_type & N_EXT))
  3698.     continue;
  3699.  
  3700.       g = (symbol *) s->n_un.n_name;
  3701.       errmsg = 0;
  3702.  
  3703.       if (!g->defined && list_unresolved_refs) /* Reference */
  3704.     {
  3705.       /* Mark as being noted by relocation warning pass.  */
  3706.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3707.  
  3708.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3709.         continue;
  3710.  
  3711.       /* Undefined symbol which we should mention */
  3712.  
  3713.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3714.         {
  3715.           errfmt = "More undefined symbol %s refs follow";
  3716.           invalidate_line_number = 1;
  3717.         }
  3718.       else
  3719.         {
  3720.           errfmt = "Undefined symbol %s referenced from %s segment";
  3721.           invalidate_line_number = 0;
  3722.         }
  3723.     }
  3724.       else                         /* Defined */
  3725.     {
  3726.       /* Potential symbol warning here */
  3727.       if (!g->warning) continue;
  3728.  
  3729.       /* Mark as being noted by relocation warning pass.  */
  3730.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3731.  
  3732.       errfmt = 0;
  3733.       errmsg = g->warning;
  3734.       invalidate_line_number = 0;
  3735.     }
  3736.  
  3737.  
  3738.       /* If errfmt == 0, errmsg has already been defined.  */
  3739.       if (errfmt != 0)
  3740.     {
  3741.       char *nm;
  3742.  
  3743.       if (!demangler || !(nm = (*demangler)(g->name)))
  3744.         nm = g->name;
  3745.       errmsg = xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3746.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3747.       if (nm != g->name)
  3748.         free (nm);
  3749.     }
  3750.  
  3751.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3752.                state_pointer);
  3753.  
  3754.       if (current->line >=0)
  3755.     {
  3756.       fprintf (outfile, "%s:%d (", current->filename,
  3757.            invalidate_line_number ? 0 : current->line);
  3758.       print_file_name (entry, outfile);
  3759.       fprintf (outfile, "): %s\n", errmsg);
  3760.     }
  3761.       else
  3762.     {
  3763.       print_file_name(entry, outfile);
  3764.       fprintf(outfile, ": %s\n", errmsg);
  3765.     }
  3766.  
  3767.       if (errfmt != 0)
  3768.     free (errmsg);
  3769.     }
  3770.  
  3771.   free (state_pointer);
  3772. }
  3773.  
  3774. /* Print on OUTFILE a list of all warnings generated by references
  3775.    and/or definitions in the file ENTRY.  List source file and line
  3776.    number if possible, just the .o file if not. */
  3777.  
  3778. void
  3779. do_file_warnings (entry, outfile)
  3780.      struct file_entry *entry;
  3781.      FILE *outfile;
  3782. {
  3783.   int number_of_syms = entry->syms_size / sizeof (struct nlist);
  3784.   unsigned char *nlist_bitvector
  3785.     = (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3786.   struct line_debug_entry *text_scan, *data_scan;
  3787.   int i;
  3788.   char *errfmt, *file_name;
  3789.   int line_number;
  3790.   int dont_allow_symbol_name;
  3791.  
  3792.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3793.  
  3794.   /* Read in the files strings if they aren't available */
  3795.   if (!entry->strings)
  3796.     {
  3797.       int desc;
  3798.  
  3799.       entry->strings = (char *) alloca (entry->strs_size);
  3800.       desc = file_open (entry);
  3801.       read_entry_strings (desc, entry);
  3802.     }
  3803.  
  3804.   read_file_relocation (entry);
  3805.  
  3806.   /* Do text warnings based on a scan through the relocation info.  */
  3807.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3808.  
  3809.   /* Do data warnings based on a scan through the relocation info.  */
  3810.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3811.  
  3812.   /* Scan through all of the nlist entries in this file and pick up
  3813.      anything that the scan through the relocation stuff didn't.  */
  3814.  
  3815.   text_scan = init_debug_scan (0, entry);
  3816.   data_scan = init_debug_scan (1, entry);
  3817.  
  3818.   for (i = 0; i < number_of_syms; i++)
  3819.     {
  3820.       struct nlist *s;
  3821.       struct glosym *g;
  3822.  
  3823.       s = entry->symbols + i;
  3824.  
  3825.       if (!(s->n_type & N_EXT))
  3826.     continue;
  3827.  
  3828.       g = (symbol *) s->n_un.n_name;
  3829.       dont_allow_symbol_name = 0;
  3830.  
  3831.       if (list_multiple_defs && g->multiply_defined)
  3832.     {
  3833.       errfmt = "Definition of symbol %s (multiply defined)";
  3834.       switch (s->n_type)
  3835.         {
  3836.         case N_TEXT | N_EXT:
  3837.           line_number = address_to_line (s->n_value, text_scan);
  3838.           file_name = text_scan[0].filename;
  3839.           break;
  3840.         case N_DATA | N_EXT:
  3841.           line_number = address_to_line (s->n_value, data_scan);
  3842.           file_name = data_scan[0].filename;
  3843.           break;
  3844.         case N_SETA | N_EXT:
  3845.         case N_SETT | N_EXT:
  3846.         case N_SETD | N_EXT:
  3847.         case N_SETB | N_EXT:
  3848.           if (g->multiply_defined == 2)
  3849.         continue;
  3850.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3851.           break;
  3852.         default:
  3853.           continue;        /* Don't print out multiple defs
  3854.                    at references.  */
  3855.         }
  3856.     }
  3857.       else if (BIT_SET_P (nlist_bitvector, i))
  3858.     continue;
  3859.       else if (list_unresolved_refs && !g->defined)
  3860.     {
  3861.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3862.         continue;
  3863.  
  3864.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3865.         errfmt = "More undefined \"%s\" refs follow";
  3866.       else
  3867.         errfmt = "Undefined symbol \"%s\" referenced";
  3868.       line_number = -1;
  3869.     }
  3870.       else if (g->warning)
  3871.     {
  3872.       /* There are two cases in which we don't want to
  3873.          do this.  The first is if this is a definition instead of
  3874.          a reference.  The second is if it's the reference used by
  3875.          the warning stabs itself.  */
  3876.       if (s->n_type != (N_EXT | N_UNDF)
  3877.           || (i && (s-1)->n_type == N_WARNING))
  3878.         continue;
  3879.  
  3880.       errfmt = g->warning;
  3881.       line_number = -1;
  3882.       dont_allow_symbol_name = 1;
  3883.     }
  3884.       else
  3885.     continue;
  3886.  
  3887.       if (line_number == -1)
  3888.     {
  3889.       print_file_name (entry, outfile);
  3890.       fprintf (outfile, ": ");
  3891.     }
  3892.       else
  3893.     {
  3894.       fprintf (outfile, "%s:%d (", file_name, line_number);
  3895.       print_file_name (entry, outfile);
  3896.       fprintf (outfile, "): ");
  3897.     }
  3898.  
  3899.       if (dont_allow_symbol_name)
  3900.     fprintf (outfile, "%s", errfmt);
  3901.       else
  3902.     {
  3903.       char *nm;
  3904.  
  3905.       if (!demangler || !(nm = (*demangler)(g->name)))
  3906.         fprintf (outfile, errfmt, g->name);
  3907.       else
  3908.         {
  3909.           fprintf (outfile, errfmt, nm);
  3910.           free (nm);
  3911.         }
  3912.     }
  3913.  
  3914.       fputc ('\n', outfile);
  3915.     }
  3916.   free (text_scan);
  3917.   free (data_scan);
  3918.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3919. }
  3920.  
  3921. do_warnings (outfile)
  3922.      FILE *outfile;
  3923. {
  3924.   list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
  3925.   list_warning_symbols = warning_count;
  3926.   list_multiple_defs = multiple_def_count != 0;
  3927.  
  3928.   if (!(list_unresolved_refs ||
  3929.     list_warning_symbols ||
  3930.     list_multiple_defs      ))
  3931.     /* No need to run this routine */
  3932.     return;
  3933.  
  3934.   each_file (do_file_warnings, outfile);
  3935.  
  3936.   if (list_unresolved_refs || list_multiple_defs)
  3937.     make_executable = 0;
  3938. }
  3939.  
  3940. #ifdef A_OUT
  3941.  
  3942. /* Stuff pertaining to creating a.out files. */
  3943.  
  3944. /* The a.out header. */
  3945.  
  3946. struct exec outheader;
  3947.  
  3948. #ifdef COFF_ENCAPSULATE
  3949. int need_coff_header;
  3950. struct coffheader coffheader;
  3951. #endif
  3952.  
  3953. /* Compute text_start and text_header_size for an a.out file.  */
  3954.  
  3955. void
  3956. initialize_a_out_text_start ()
  3957. {
  3958.   int magic;
  3959.  
  3960.   switch (output_style)
  3961.     {
  3962.     case OUTPUT_RELOCATABLE:
  3963.     case OUTPUT_WRITABLE_TEXT:
  3964.       magic = OMAGIC;
  3965.       break;
  3966.     case OUTPUT_READONLY_TEXT:
  3967. #ifdef NMAGIC
  3968.       magic = NMAGIC;
  3969.       break;
  3970. #endif
  3971.     case OUTPUT_DEMAND_PAGED:
  3972.       magic = ZMAGIC;
  3973.       break;
  3974.     default:
  3975.       fatal ("unknown output style found (bug in ld)", (char *) 0);
  3976.       break;
  3977.     }
  3978.  
  3979.   /* Determine whether to count the header as part of
  3980.      the text size, and initialize the text size accordingly.
  3981.      This depends on the kind of system and on the output format selected.  */
  3982.   N_SET_MAGIC (outheader, magic);
  3983. #ifdef INITIALIZE_HEADER
  3984.   INITIALIZE_HEADER;
  3985. #endif
  3986.  
  3987.   text_header_size = sizeof (struct exec);
  3988. #ifdef COFF_ENCAPSULATE
  3989.   /* Don't write the coff header for the output of ld -A (since
  3990.      it is not executable by the kernel anyway).  */
  3991.   if (output_style != OUTPUT_RELOCATABLE && !file_table[0].just_syms_flag)
  3992.     {
  3993.       need_coff_header = 1;
  3994.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  3995.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  3996.       text_header_size += sizeof (struct coffheader);
  3997.     }
  3998. #endif
  3999.   if (text_header_size <= N_TXTOFF (outheader))
  4000.     text_header_size = 0;
  4001.   else
  4002.     text_header_size -= N_TXTOFF (outheader);
  4003.  
  4004. #ifdef _N_BASEADDR
  4005.   /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */
  4006.   outheader.a_entry = N_PAGSIZ(outheader);
  4007. #endif
  4008.  
  4009.   if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4010.     text_start = N_TXTADDR (outheader);
  4011. }
  4012.  
  4013. /* Compute data_start once text_size is known. */
  4014.  
  4015. void
  4016. initialize_a_out_data_start ()
  4017. {
  4018.   outheader.a_text = text_size;
  4019. #if TARGET_MACHINE==TARGET_SEQUENT
  4020.   outheader.a_text += N_ADDRADJ (outheader);
  4021.   if (entry_symbol == 0)
  4022.     entry_symbol = getsym ("start");
  4023. #endif
  4024.   if (! Tdata_flag_specified)
  4025.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  4026. }
  4027.  
  4028. /* Compute offsets of various pieces of the a.out output file.  */
  4029.  
  4030. void
  4031. compute_a_out_section_offsets ()
  4032. {
  4033.   outheader.a_data = data_size;
  4034.   outheader.a_bss = bss_size;
  4035.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  4036.                : text_start + text_header_size);
  4037.  
  4038. #ifdef COFF_ENCAPSULATE
  4039.   if (need_coff_header)
  4040.     {
  4041.       /* We are encapsulating BSD format within COFF format.  */
  4042.       struct coffscn *tp, *dp, *bp;
  4043.  
  4044.       tp = &coffheader.scns[0];
  4045.       dp = &coffheader.scns[1];
  4046.       bp = &coffheader.scns[2];
  4047.  
  4048.       strcpy (tp->s_name, ".text");
  4049.       tp->s_paddr = text_start;
  4050.       tp->s_vaddr = text_start;
  4051.       tp->s_size = text_size;
  4052.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  4053.       tp->s_relptr = 0;
  4054.       tp->s_lnnoptr = 0;
  4055.       tp->s_nreloc = 0;
  4056.       tp->s_nlnno = 0;
  4057.       tp->s_flags = 0x20;
  4058.       strcpy (dp->s_name, ".data");
  4059.       dp->s_paddr = data_start;
  4060.       dp->s_vaddr = data_start;
  4061.       dp->s_size = data_size;
  4062.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  4063.       dp->s_relptr = 0;
  4064.       dp->s_lnnoptr = 0;
  4065.       dp->s_nreloc = 0;
  4066.       dp->s_nlnno = 0;
  4067.       dp->s_flags = 0x40;
  4068.       strcpy (bp->s_name, ".bss");
  4069.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  4070.       bp->s_vaddr = bp->s_paddr;
  4071.       bp->s_size = bss_size;
  4072.       bp->s_scnptr = 0;
  4073.       bp->s_relptr = 0;
  4074.       bp->s_lnnoptr = 0;
  4075.       bp->s_nreloc = 0;
  4076.       bp->s_nlnno = 0;
  4077.       bp->s_flags = 0x80;
  4078.  
  4079.       coffheader.f_magic = COFF_MAGIC;
  4080.       coffheader.f_nscns = 3;
  4081.       /* store an unlikely time so programs can
  4082.        * tell that there is a bsd header
  4083.        */
  4084.       coffheader.f_timdat = 1;
  4085.       coffheader.f_symptr = 0;
  4086.       coffheader.f_nsyms = 0;
  4087.       coffheader.f_opthdr = 28;
  4088.       coffheader.f_flags = 0x103;
  4089.       /* aouthdr */
  4090.       coffheader.magic = ZMAGIC;
  4091.       coffheader.vstamp = 0;
  4092.       coffheader.tsize = tp->s_size;
  4093.       coffheader.dsize = dp->s_size;
  4094.       coffheader.bsize = bp->s_size;
  4095.       coffheader.entry = outheader.a_entry;
  4096.       coffheader.text_start = tp->s_vaddr;
  4097.       coffheader.data_start = dp->s_vaddr;
  4098.     }
  4099. #endif
  4100.  
  4101.   if (strip_symbols == STRIP_ALL)
  4102.     nsyms = 0;
  4103.   else
  4104.     {
  4105.       nsyms = (defined_global_sym_count
  4106.            + undefined_global_sym_count);
  4107.       if (discard_locals == DISCARD_L)
  4108.     nsyms += non_L_local_sym_count;
  4109.       else if (discard_locals == DISCARD_NONE)
  4110.     nsyms += local_sym_count;
  4111.       /* One extra for following reference on indirects */
  4112.       if (output_style == OUTPUT_RELOCATABLE)
  4113. #ifndef NeXT
  4114.     nsyms += set_symbol_count + global_indirect_count;
  4115. #else
  4116.         nsyms += set_symbol_count;
  4117. #endif
  4118.     }
  4119.  
  4120.   if (strip_symbols == STRIP_NONE)
  4121.     nsyms += debugger_sym_count;
  4122.  
  4123.   outheader.a_syms = nsyms * sizeof (struct nlist);
  4124.  
  4125.   if (output_style == OUTPUT_RELOCATABLE)
  4126.     {
  4127.       outheader.a_trsize = text_reloc_size;
  4128.       outheader.a_drsize = data_reloc_size;
  4129.     }
  4130.   else
  4131.     {
  4132.       outheader.a_trsize = 0;
  4133.       outheader.a_drsize = 0;
  4134.     }
  4135.  
  4136.   /* Initialize the various file offsets.  */
  4137.  
  4138.   output_text_offset = N_TXTOFF (outheader);
  4139. #ifdef N_DATOFF
  4140.   output_data_offset = N_DATOFF (outheader);
  4141. #else
  4142.   output_data_offset = output_text_offset + text_size;
  4143. #endif
  4144. #ifdef N_TRELOFF
  4145.   output_trel_offset = N_TRELOFF (outheader);
  4146. #else
  4147.   output_trel_offset = output_data_offset + data_size;
  4148. #endif
  4149. #ifdef N_DRELOFF
  4150.   output_drel_offset = N_DRELOFF (outheader);
  4151. #else
  4152.   output_drel_offset = output_trel_offset + text_reloc_size;
  4153. #endif
  4154.   output_syms_offset = N_SYMOFF (outheader);
  4155.   output_strs_offset = N_STROFF (outheader);
  4156. }
  4157.  
  4158. /* Compute more section offsets once the size of the string table is known.  */
  4159.  
  4160. void
  4161. compute_more_a_out_section_offsets ()
  4162. {
  4163.   output_symseg_offset = output_strs_offset + output_strs_size;
  4164. }
  4165.  
  4166. /* Write the a.out header once everything else is known.  */
  4167.  
  4168. void
  4169. write_a_out_header ()
  4170. {
  4171.   lseek (outdesc, 0L, 0);
  4172.  
  4173. #ifdef COFF_ENCAPSULATE
  4174.   if (need_coff_header)
  4175.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  4176. #endif
  4177.  
  4178. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4179.   fix_exec_header_byte_order(&outheader);
  4180. #endif
  4181.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  4182. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4183.   fix_exec_header_byte_order(&outheader);
  4184. #endif
  4185.  
  4186.   /* Output whatever padding is required in the executable file
  4187.      between the header and the start of the text.  */
  4188.  
  4189. #ifndef COFF_ENCAPSULATE
  4190.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  4191. #endif
  4192. }
  4193.  
  4194. #endif
  4195.  
  4196. #ifdef MACH_O
  4197.  
  4198. /* Stuff pertaining to creating Mach-O files. */
  4199.  
  4200. /* Convert the Mach-O style n_sect references into something the rest
  4201.    of the loader can understand.  */
  4202.  
  4203. void
  4204. translate_mach_o_symbols (entry)
  4205.      struct file_entry *entry;
  4206. {
  4207.   int i, n, g;
  4208.   struct nlist *sym;
  4209.  
  4210.   n = entry->syms_size / sizeof (struct nlist);
  4211.   for (i = 0; i < n; ++i)
  4212.     if (((sym = &entry->symbols[i])->n_type & ~N_EXT) == N_SECT)
  4213.       {
  4214.     if (sym->n_sect == entry->text_ordinal)
  4215.       sym->n_type = (sym->n_type & N_EXT) | N_TEXT;
  4216.     else if (sym->n_sect == entry->data_ordinal)
  4217.       sym->n_type = (sym->n_type & N_EXT) | N_DATA;
  4218.     else if (sym->n_sect == entry->bss_ordinal)
  4219.       sym->n_type = (sym->n_type & N_EXT) | N_BSS;
  4220.     else
  4221.       fatal_with_file ("unknown section referenced in symbols of ", entry);
  4222.     sym->n_sect = 0;
  4223.       }
  4224.     else if ((sym = &entry->symbols[i])->n_type == N_SLINE)
  4225.       {
  4226.     if (sym->n_sect == entry->text_ordinal)
  4227.       sym->n_type = N_SLINE;
  4228.     else if (sym->n_sect == entry->data_ordinal)
  4229.       sym->n_type = N_DSLINE;
  4230.     else if (sym->n_sect == entry->bss_ordinal)
  4231.       sym->n_type = N_BSLINE;
  4232.     else
  4233.       fatal_with_file ("unknown section referenced in debugging symbols of ", entry);
  4234.       }
  4235. }
  4236.  
  4237. /* Convert Mach-O style relocation info into a.out style relocation
  4238.    info internally.  */
  4239. void
  4240. translate_mach_o_relocation (entry, reloc, count)
  4241.      struct file_entry *entry;
  4242.      struct relocation_info *reloc;
  4243.      int count;
  4244. {
  4245.   int i;
  4246.  
  4247.   for (i = 0; i < count; ++i)
  4248.     if (!RELOC_EXTERN_P(&reloc[i]))
  4249.       if (RELOC_TYPE(&reloc[i]) == R_ABS)
  4250.     RELOC_TYPE(&reloc[i]) = N_ABS;
  4251.       else if (RELOC_TYPE(&reloc[i]) == entry->text_ordinal)
  4252.     RELOC_TYPE(&reloc[i]) = N_TEXT;
  4253.       else if (RELOC_TYPE(&reloc[i]) == entry->data_ordinal)
  4254.     RELOC_TYPE(&reloc[i]) = N_DATA;
  4255.       else if (RELOC_TYPE(&reloc[i]) == entry->bss_ordinal)
  4256.     RELOC_TYPE(&reloc[i]) = N_BSS;
  4257.       else
  4258.     fatal_with_file ("unknown section ordinal in relocation info of ", entry);
  4259. }
  4260.  
  4261. /* Header structure for OUTPUT_RELOCATABLE.  */
  4262.  
  4263. struct
  4264. {
  4265.   struct mach_header header;
  4266.   struct segment_command segment;
  4267.   struct section text;
  4268.   struct section data;
  4269.   struct section bss;
  4270.   struct symtab_command symtab;
  4271. #ifdef LC_SYMSEG
  4272.   struct symseg_command symseg;
  4273. #endif
  4274. } m_object;
  4275.  
  4276. #ifdef NeXT
  4277. #define CPU_TYPE CPU_TYPE_MC68030
  4278. #define CPU_SUBTYPE CPU_SUBTYPE_NeXT
  4279. #define THREAD_FLAVOR NeXT_THREAD_STATE_REGS
  4280. #define THREAD_COUNT NeXT_THREAD_STATE_REGS_COUNT
  4281. typedef struct NeXT_thread_state_regs thread_state;
  4282. #define thread_state_entry_field pc
  4283. #endif
  4284.  
  4285. /* Header structure for all executable output forms.  */
  4286.  
  4287. struct
  4288. {
  4289.   struct mach_header header;
  4290.   struct segment_command pagezero;
  4291.   struct segment_command text_segment;
  4292.   struct section text;
  4293.   struct segment_command data_segment;
  4294.   struct section data;
  4295.   struct section bss;
  4296.   struct thread_command unixthread;
  4297.   unsigned long int flavor;
  4298.   unsigned long int count;
  4299.   thread_state state;
  4300.   struct symtab_command symtab;
  4301. #ifdef LC_SYMSEG
  4302.   struct symseg_command symseg;
  4303. #endif
  4304. } m_exec;
  4305.  
  4306. /* Compute text_start and text_header_size for an a.out file.  */
  4307.  
  4308. void
  4309. initialize_mach_o_text_start ()
  4310. {
  4311.   if (output_style != OUTPUT_RELOCATABLE)
  4312.     {
  4313.       text_header_size = sizeof m_exec;
  4314.       if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4315.     /* We reserve the first page of an executable to trap NULL dereferences.  */
  4316.     text_start = page_size;
  4317.     }
  4318. }
  4319.  
  4320. /* Compute data_start once text_size is known.  */
  4321.  
  4322. void
  4323. initialize_mach_o_data_start ()
  4324. {
  4325.   if (! Tdata_flag_specified)
  4326.     data_start = text_start + text_size;
  4327. }
  4328.  
  4329. /* Compute offsets of various pieces of the Mach-O output file.  */
  4330. void
  4331. compute_mach_o_section_offsets ()
  4332. {
  4333.   int header_size, trsize, drsize;
  4334.  
  4335.   switch (output_style)
  4336.     {
  4337.     case OUTPUT_RELOCATABLE:
  4338.       header_size = sizeof m_object;
  4339.       break;
  4340.     default:
  4341.       header_size = sizeof m_exec;
  4342.       break;
  4343.     }
  4344.  
  4345.   if (strip_symbols == STRIP_ALL)
  4346.     nsyms = 0;
  4347.   else
  4348.     {
  4349.       nsyms = (defined_global_sym_count
  4350.            + undefined_global_sym_count);
  4351.       if (discard_locals == DISCARD_L)
  4352.     nsyms += non_L_local_sym_count;
  4353.       else if (discard_locals == DISCARD_NONE)
  4354.     nsyms += local_sym_count;
  4355.       /* One extra for following reference on indirects */
  4356.       if (output_style == OUTPUT_RELOCATABLE)
  4357. #if TARGET_MACHINEN==TARGET_NeXT
  4358.         nsyms += set_symbol_count;
  4359. #else
  4360.     nsyms += set_symbol_count + global_indirect_count;
  4361. #endif
  4362.     }
  4363.  
  4364.   if (strip_symbols == STRIP_NONE)
  4365.     nsyms += debugger_sym_count;
  4366.  
  4367.   if (output_style != OUTPUT_RELOCATABLE)
  4368.     output_text_offset = header_size;
  4369.   output_data_offset = output_text_offset + text_size;
  4370.   output_trel_offset = output_data_offset + data_size;
  4371.   if (output_style == OUTPUT_RELOCATABLE)
  4372.     trsize = text_reloc_size, drsize = data_reloc_size;
  4373.   else
  4374.     trsize = drsize = 0;
  4375.   output_drel_offset = output_trel_offset + trsize;
  4376.   output_syms_offset = output_drel_offset + drsize;
  4377.   output_strs_offset = output_syms_offset + nsyms * sizeof (struct nlist);
  4378. }
  4379.  
  4380. /* Compute more section offsets once the size of the string table is known.  */
  4381. void
  4382. compute_more_mach_o_section_offsets ()
  4383. {
  4384.   output_symseg_offset = output_strs_offset + output_strs_size;
  4385. }
  4386.  
  4387. /* Write the Mach-O header once everything else is known.  */
  4388.  
  4389. void
  4390. write_mach_o_header ()
  4391. {
  4392.   struct mach_header header;
  4393.   struct section text, data, bss;
  4394.   struct symtab_command symtab;
  4395. #ifdef LC_SYMSEG
  4396.   struct symseg_command symseg;
  4397. #endif
  4398.   thread_state state;
  4399.  
  4400.   lseek (outdesc, 0L, 0);
  4401.  
  4402.  
  4403.   header.magic = MH_MAGIC;
  4404.   header.cputype = CPU_TYPE;
  4405.   header.cpusubtype = CPU_SUBTYPE;
  4406.   header.filetype = output_style == OUTPUT_RELOCATABLE ? MH_OBJECT : MH_EXECUTE;
  4407. #ifdef LC_SYMSEG
  4408.   switch (output_style)
  4409.     {
  4410.     case OUTPUT_RELOCATABLE:
  4411.       header.ncmds = 3;
  4412.       header.sizeofcmds = sizeof m_object - sizeof header;
  4413.       break;
  4414.     default:
  4415.       header.ncmds = 6;
  4416.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4417.       break;
  4418.     }
  4419. #else
  4420.   switch (output_style)
  4421.     {
  4422.     case OUTPUT_RELOCATABLE:
  4423.       header.ncmds = 2;
  4424.       header.sizeofcmds = sizeof m_object - sizeof header;
  4425.       break;
  4426.     default:
  4427.       header.ncmds = 5;
  4428.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4429.       break;
  4430.     }
  4431. #endif
  4432.   header.flags = undefined_global_sym_count ? 0 : MH_NOUNDEFS;
  4433.  
  4434.   bzero((char *) &text, sizeof text);
  4435.   strncpy(text.sectname, SECT_TEXT, sizeof text.sectname);
  4436.   strncpy(text.segname, SEG_TEXT, sizeof text.segname);
  4437.   text.addr = text_start;
  4438.   text.size = text_size;
  4439.   text.offset = output_text_offset;
  4440.   text.align = text.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4441.   text.reloff = output_trel_offset;
  4442.   text.nreloc = output_style == OUTPUT_RELOCATABLE
  4443.     ? text_reloc_size / sizeof (struct relocation_info) : 0;
  4444.   text.flags = 0;
  4445.  
  4446.   bzero((char *) &data, sizeof data);
  4447.   strncpy(data.sectname, SECT_DATA, sizeof data.sectname);
  4448.   strncpy(data.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4449.       sizeof data.segname);
  4450.   data.addr = data_start;
  4451.   data.size = data_size;
  4452.   data.offset = output_data_offset;
  4453.   data.align = data.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4454.   data.reloff = output_drel_offset;
  4455.   data.nreloc = output_style == OUTPUT_RELOCATABLE
  4456.     ? data_reloc_size / sizeof (struct relocation_info) : 0;
  4457.   data.flags = 0;
  4458.  
  4459.   bzero((char *) &bss, sizeof bss);
  4460.   strncpy(bss.sectname, SECT_BSS, sizeof data.sectname);
  4461.   strncpy(bss.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4462.       sizeof bss.segname);
  4463.   bss.addr = data_start + data_size;
  4464.   bss.size = bss_size;
  4465.   bss.align = bss.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4466.   bss.reloff = 0;
  4467.   bss.nreloc = 0;
  4468.   bss.flags = S_ZEROFILL;
  4469.  
  4470.   symtab.cmd = LC_SYMTAB;
  4471.   symtab.cmdsize = sizeof symtab;
  4472.   symtab.symoff = output_syms_offset;
  4473.   symtab.nsyms = output_syms_size / sizeof (struct nlist);
  4474.   symtab.stroff = output_strs_offset;
  4475.   symtab.strsize = output_strs_size;
  4476.  
  4477. #ifdef LC_SYMSEG
  4478.   symseg.cmd = LC_SYMSEG;
  4479.   symseg.cmdsize = sizeof symseg;
  4480.   symseg.offset = output_symseg_offset;
  4481.   symseg.size = output_symseg_size;
  4482. #endif
  4483.  
  4484.   switch (output_style)
  4485.     {
  4486.     case OUTPUT_RELOCATABLE:
  4487.       m_object.header = header;
  4488.       m_object.segment.cmd = LC_SEGMENT;
  4489.       m_object.segment.cmdsize = sizeof (struct segment_command) + 3 * sizeof (struct section);
  4490.       strncpy(m_object.segment.segname, SEG_TEXT, sizeof m_object.segment.segname);
  4491.       m_object.segment.vmaddr = 0;
  4492.       m_object.segment.vmsize = text.size + data.size + bss.size;
  4493.       m_object.segment.fileoff = text.offset;
  4494.       m_object.segment.filesize = text.size + data.size;
  4495.       m_object.segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4496.       m_object.segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4497.       m_object.segment.nsects = 3;
  4498.       m_object.segment.flags = 0;
  4499.       m_object.text = text;
  4500.       m_object.data = data;
  4501.       m_object.bss = bss;
  4502.       m_object.symtab = symtab;
  4503. #ifdef LC_SYMSEG
  4504.       m_object.symseg = symseg;
  4505. #endif
  4506.       mywrite((char *) &m_object, 1, sizeof m_object, outdesc);
  4507.       break;
  4508.  
  4509.     case 'Z':
  4510.       data_gap = parse (arg, "%x", "invalid argument to -Z");
  4511.       if (data_gap % page_size)
  4512.       fatal("-Z argument not a multiple of page size", 0);
  4513.       Z_flag_specified = 1;
  4514.       return;
  4515.  
  4516.     default:
  4517.       m_exec.header = header;
  4518.       m_exec.pagezero.cmd = LC_SEGMENT;
  4519.       m_exec.pagezero.cmdsize = sizeof (struct segment_command);
  4520.       strncpy(m_exec.pagezero.segname, SEG_PAGEZERO, sizeof m_exec.pagezero.segname);
  4521.       m_exec.pagezero.vmaddr = 0;
  4522.       m_exec.pagezero.vmsize = page_size;
  4523.       m_exec.pagezero.fileoff = 0;
  4524.       m_exec.pagezero.filesize = 0;
  4525.       m_exec.pagezero.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4526.       m_exec.pagezero.initprot = 0;
  4527.       m_exec.pagezero.nsects = 0;
  4528.       m_exec.pagezero.flags = 0;
  4529.       m_exec.text_segment.cmd = LC_SEGMENT;
  4530.       m_exec.text_segment.cmdsize = sizeof (struct segment_command) + sizeof (struct section);
  4531.       strncpy(m_exec.text_segment.segname, SEG_TEXT, sizeof m_exec.text_segment.segname);
  4532.       m_exec.text_segment.vmaddr = text_start;
  4533.       m_exec.text_segment.vmsize = text_size;
  4534.       m_exec.text_segment.fileoff = output_text_offset;
  4535.       m_exec.text_segment.filesize = text_size;
  4536.       m_exec.text_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4537.       m_exec.text_segment.initprot = VM_PROT_READ | VM_PROT_EXECUTE;
  4538.       if (output_style == OUTPUT_WRITABLE_TEXT)
  4539.     m_exec.text_segment.initprot |= VM_PROT_WRITE;
  4540.       m_exec.text_segment.nsects = 1;
  4541.       m_exec.text_segment.flags = 0;
  4542.       m_exec.text = text;
  4543.       m_exec.data_segment.cmd = LC_SEGMENT;
  4544.       m_exec.data_segment.cmdsize = sizeof (struct segment_command) + 2 * sizeof (struct section);
  4545.       strncpy(m_exec.data_segment.segname, SEG_DATA, sizeof m_exec.data_segment.segname);
  4546.       m_exec.data_segment.vmaddr = data_start;
  4547.       m_exec.data_segment.vmsize = data_size + bss_size;
  4548.       m_exec.data_segment.fileoff = output_data_offset;
  4549.       m_exec.data_segment.filesize = data_size;
  4550.       m_exec.data_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4551.       m_exec.data_segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4552.       m_exec.data_segment.nsects = 2;
  4553.       m_exec.data_segment.flags = 0;
  4554.       m_exec.data = data;
  4555.       m_exec.bss = bss;
  4556.       m_exec.unixthread.cmd = LC_UNIXTHREAD;
  4557.       m_exec.unixthread.cmdsize
  4558.     = sizeof (struct thread_command) + 2 * sizeof (long int) + sizeof (thread_state);
  4559.       m_exec.flavor = THREAD_FLAVOR;
  4560.       m_exec.count = THREAD_COUNT;
  4561.       m_exec.state.thread_state_entry_field = entry_symbol
  4562.     ? entry_symbol->value : text_start + text_header_size;
  4563.       m_exec.symtab = symtab;
  4564. #ifdef LC_SYMSEG
  4565.       m_exec.symseg = symseg;
  4566. #endif
  4567.       mywrite((char *) &m_exec, 1, sizeof m_exec, outdesc);
  4568.       break;
  4569.     }
  4570. }
  4571.  
  4572.  
  4573. /* Translate a.out style symbols into Mach-O style symbols.  */
  4574.  
  4575. void
  4576. generate_mach_o_symbols (syms, nsyms)
  4577.      struct nlist *syms;
  4578.      int nsyms;
  4579. {
  4580.   int i;
  4581.  
  4582.   for (i = 0; i < nsyms; ++i)
  4583.     switch (syms[i].n_type)
  4584.       {
  4585.       case N_TEXT:
  4586.       case N_TEXT | N_EXT:
  4587.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4588.     syms[i].n_sect = 1;    /* text section ordinal */
  4589.     break;
  4590.       case N_DATA:
  4591.       case N_DATA | N_EXT:
  4592.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4593.     syms[i].n_sect = 2;    /* data section ordinal */
  4594.     break;
  4595.       case N_BSS:
  4596.       case N_BSS | N_EXT:
  4597.     syms[i].n_type = syms[i].n_type & N_EXT | N_BSS;
  4598.     syms[i].n_sect = 3;    /* bss section ordinal */
  4599.     break;
  4600.       case N_SLINE:
  4601.     syms[i].n_type = N_SLINE;
  4602.     syms[i].n_sect = 1;    /* text section ordinal */
  4603.     break;
  4604.       case N_DSLINE:
  4605.     syms[i].n_type = N_SLINE;
  4606.     syms[i].n_sect = 2;    /* data section ordinal */
  4607.     break;
  4608.       case N_BSLINE:
  4609.     syms[i].n_type = N_SLINE;
  4610.     syms[i].n_sect = 3;    /* bss section ordinal */
  4611.     break;
  4612.       }
  4613. }
  4614.  
  4615. /* Translate a.out style relocation info into Mach-O style relocation
  4616.    info.  */
  4617.  
  4618. void
  4619. generate_mach_o_relocations (reloc, nreloc)
  4620.      struct relocation_info *reloc;
  4621.      int nreloc;
  4622. {
  4623.   int i;
  4624.  
  4625.   for (i = 0; i < nreloc; ++i)
  4626.     if (!RELOC_EXTERN_P (&reloc[i]))
  4627.       switch (RELOC_TYPE (&reloc[i]))
  4628.     {
  4629.     case N_ABS:
  4630.     case N_ABS | N_EXT:
  4631.       RELOC_TYPE (&reloc[i]) = R_ABS;
  4632.       break;
  4633.     case N_TEXT:
  4634.     case N_TEXT | N_EXT:
  4635.       RELOC_TYPE (&reloc[i]) = 1; /* output text section ordinal */
  4636.       break;
  4637.     case N_DATA:
  4638.     case N_DATA | N_EXT:
  4639.       RELOC_TYPE (&reloc[i]) = 2; /* output data section ordinal */
  4640.       break;
  4641.     case N_BSS:
  4642.     case N_BSS | N_EXT:
  4643.       RELOC_TYPE (&reloc[i]) = 3; /* output bss section ordinal */
  4644.       break;
  4645.     }
  4646. }
  4647.  
  4648. #endif
  4649.  
  4650. /* The following functions are simple switches according to the
  4651.    output style.  */
  4652.  
  4653. /* Compute text_start and text_header_size as appropriate for the
  4654.    output format.  */
  4655.  
  4656. void
  4657. initialize_text_start ()
  4658. {
  4659. #ifdef A_OUT
  4660.   if (output_file_type == IS_A_OUT)
  4661.     {
  4662.       initialize_a_out_text_start ();
  4663.       return;
  4664.     }
  4665. #endif
  4666. #ifdef MACH_O
  4667.   if (output_file_type == IS_MACH_O)
  4668.     {
  4669.       initialize_mach_o_text_start ();
  4670.       return;
  4671.     }
  4672. #endif
  4673.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4674. }
  4675.  
  4676. /* Initialize data_start as appropriate to the output format, once text_size
  4677.    is known.  */
  4678.  
  4679. void
  4680. initialize_data_start ()
  4681. {
  4682. #ifdef A_OUT
  4683.   if (output_file_type == IS_A_OUT)
  4684.     {
  4685.       initialize_a_out_data_start ();
  4686.       return;
  4687.     }
  4688. #endif
  4689. #ifdef MACH_O
  4690.   if (output_file_type == IS_MACH_O)
  4691.     {
  4692.       initialize_mach_o_data_start ();
  4693.       return;
  4694.     }
  4695. #endif
  4696.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4697. }
  4698.  
  4699. /* Compute offsets of the various sections within the output file.  */
  4700.  
  4701. void
  4702. compute_section_offsets ()
  4703. {
  4704. #ifdef A_OUT
  4705.   if (output_file_type == IS_A_OUT)
  4706.     {
  4707.       compute_a_out_section_offsets ();
  4708.       return;
  4709.     }
  4710. #endif
  4711. #ifdef MACH_O
  4712.   if (output_file_type == IS_MACH_O)
  4713.     {
  4714.       compute_mach_o_section_offsets ();
  4715.       return;
  4716.     }
  4717. #endif
  4718.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4719. }
  4720.  
  4721. /* Compute more section offsets, once the size of the string table
  4722.    is finalized.  */
  4723. void
  4724. compute_more_section_offsets ()
  4725. {
  4726. #ifdef A_OUT
  4727.   if (output_file_type == IS_A_OUT)
  4728.     {
  4729.       compute_more_a_out_section_offsets ();
  4730.       return;
  4731.     }
  4732. #endif
  4733. #ifdef MACH_O
  4734.   if (output_file_type == IS_MACH_O)
  4735.     {
  4736.       compute_more_mach_o_section_offsets ();
  4737.       return;
  4738.     }
  4739. #endif
  4740.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4741. }
  4742.  
  4743. /* Write the output file header, once everything is known.  */
  4744. void
  4745. write_header ()
  4746. {
  4747. #ifdef A_OUT
  4748.   if (output_file_type == IS_A_OUT)
  4749.     {
  4750.       write_a_out_header ();
  4751.       return;
  4752.     }
  4753. #endif
  4754. #ifdef MACH_O
  4755.   if (output_file_type == IS_MACH_O)
  4756.     {
  4757.       write_mach_o_header ();
  4758.       return;
  4759.     }
  4760. #endif
  4761.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4762. }
  4763.  
  4764. /* Write the output file */
  4765.  
  4766. void
  4767. write_output ()
  4768. {
  4769.   struct stat statbuf;
  4770.   int filemode, mask;
  4771.  
  4772.   /* Remove the old file in case it is owned by someone else.
  4773.      This prevents spurious "not owner" error messages.
  4774.      Don't check for errors from unlink; we don't really care
  4775.      whether it worked.
  4776.  
  4777.      Note that this means that if the output file is hard linked,
  4778.      the other names will still have the old contents.  This is
  4779.      the way Unix ld works; I'm going to consider it a feature.  */
  4780.   (void) unlink (output_filename);
  4781.   
  4782.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4783.   if (outdesc < 0) perror_name (output_filename);
  4784.  
  4785.   if (fstat (outdesc, &statbuf) < 0)
  4786.     perror_name (output_filename);
  4787.  
  4788.   filemode = statbuf.st_mode;
  4789.  
  4790.   chmod (output_filename, filemode & ~0111);
  4791.  
  4792.   /* Calculate the offsets of the various pieces of the output file.  */
  4793.   compute_section_offsets ();
  4794.  
  4795.   /* Output the text and data segments, relocating as we go.  */
  4796.   write_text ();
  4797.   write_data ();
  4798.  
  4799.   /* Output the merged relocation info, if requested with `-r'.  */
  4800.   if (output_style == OUTPUT_RELOCATABLE)
  4801.     write_rel ();
  4802.  
  4803.   /* Output the symbol table (both globals and locals).  */
  4804.   write_syms ();
  4805.  
  4806.   /* At this point the total size of the symbol table and string table
  4807.      are finalized.  */
  4808.   compute_more_section_offsets ();
  4809.  
  4810.   /* Copy any GDB symbol segments from input files.  */
  4811.   write_symsegs ();
  4812.  
  4813.   /* Now that everything is known about the output file, write its header.  */
  4814.   write_header ();
  4815.  
  4816.   close (outdesc);
  4817.  
  4818.   mask = umask (0);
  4819.   umask (mask);
  4820.  
  4821.   if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
  4822.     perror_name (output_filename);
  4823. }
  4824.  
  4825. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4826.  
  4827. /* Relocate the text segment of each input file
  4828.    and write to the output file.  */
  4829.  
  4830. void
  4831. write_text ()
  4832. {
  4833.   if (trace_files)
  4834.     fprintf (stderr, "Copying and relocating text:\n\n");
  4835.  
  4836.   lseek (outdesc, output_text_offset + text_header_size, 0);
  4837.  
  4838.   each_full_file (copy_text, 0);
  4839.   file_close ();
  4840.  
  4841.   if (trace_files)
  4842.     fprintf (stderr, "\n");
  4843.  
  4844.   padfile (text_pad, outdesc);
  4845. }
  4846.  
  4847. /* Read in all of the relocation information */
  4848.  
  4849. void
  4850. read_relocation ()
  4851. {
  4852.   each_full_file (read_file_relocation, 0);
  4853. }
  4854.  
  4855. /* Read in the relocation sections of ENTRY if necessary */
  4856.  
  4857. void
  4858. read_file_relocation (entry)
  4859.      struct file_entry *entry;
  4860. {
  4861.   register struct relocation_info *reloc;
  4862.   int desc;
  4863.   int read_return;
  4864.  
  4865.   desc = -1;
  4866.   if (!entry->textrel)
  4867.     {
  4868.       reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
  4869.       desc = file_open (entry);
  4870.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4871.       if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
  4872.     {
  4873.       fprintf (stderr, "Return from read: %d\n", read_return);
  4874.       fatal_with_file ("premature eof in text relocation of ", entry);
  4875.     }
  4876. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4877.       target_to_host_reloc_byte_order(reloc,
  4878.     entry->text_reloc_size/sizeof(*reloc));
  4879. #endif
  4880.       entry->textrel = reloc;
  4881.     }
  4882.  
  4883.   if (!entry->datarel)
  4884.     {
  4885.       reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
  4886.       if (desc == -1) desc = file_open (entry);
  4887.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  4888.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  4889.     fatal_with_file ("premature eof in data relocation of ", entry);
  4890. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4891.       target_to_host_reloc_byte_order(reloc,
  4892.     entry->data_reloc_size/sizeof(*reloc));
  4893. #endif
  4894.       entry->datarel = reloc;
  4895.     }
  4896.  
  4897. #ifdef MACH_O
  4898.   if (entry->file_type == IS_MACH_O)
  4899.     {
  4900.       translate_mach_o_relocation (entry, entry->textrel,
  4901.                    entry->text_reloc_size / sizeof (struct relocation_info));
  4902.       translate_mach_o_relocation (entry, entry->datarel,
  4903.                    entry->data_reloc_size / sizeof (struct relocation_info));
  4904.     }
  4905. #endif
  4906.  
  4907.  
  4908.   if (T_flag_specified)
  4909.       padfile (text_start - sizeof(struct exec), outdesc);
  4910.  
  4911. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4912.       target_to_host_reloc_byte_order(reloc,
  4913.     entry->text_reloc_size/sizeof(*reloc));
  4914. #endif
  4915. }
  4916.  
  4917. /* Read the text segment contents of ENTRY, relocate them,
  4918.    and write the result to the output file.
  4919.    If `-r', save the text relocation for later reuse.  */
  4920.  
  4921. void
  4922. copy_text (entry)
  4923.      struct file_entry *entry;
  4924. {
  4925.   register char *bytes;
  4926.   register int desc;
  4927.   register struct relocation_info *reloc;
  4928.  
  4929.   if (trace_files)
  4930.     prline_file_name (entry, stderr);
  4931.  
  4932.   desc = file_open (entry);
  4933.  
  4934.   /* Allocate space for the file's text section */
  4935.  
  4936.   bytes = (char *) alloca (entry->text_size);
  4937.  
  4938.   /* Deal with relocation information however is appropriate */
  4939.  
  4940.   if (entry->textrel)  reloc = entry->textrel;
  4941.   else if (output_style == OUTPUT_RELOCATABLE)
  4942.     {
  4943.       read_file_relocation (entry);
  4944.       reloc = entry->textrel;
  4945.     }
  4946.   else
  4947.     {
  4948.       reloc = (struct relocation_info *) alloca (entry->text_reloc_size);
  4949.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4950.       if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
  4951.     fatal_with_file ("premature eof in text relocation of ", entry);
  4952. #ifdef MACH_O
  4953.       if (entry->file_type == IS_MACH_O)
  4954.     translate_mach_o_relocation (entry, reloc,
  4955.                      entry->text_reloc_size / sizeof (struct relocation_info));
  4956. #else
  4957. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4958.       target_to_host_reloc_byte_order(reloc,
  4959.       entry->text_reloc_size/sizeof(*reloc));
  4960. #endif
  4961. #endif    
  4962.     }
  4963.  
  4964.   /* Read the text section into core.  */
  4965.  
  4966.   lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
  4967.   if (entry->text_size != read (desc, bytes, entry->text_size))
  4968.     fatal_with_file ("premature eof in text section of ", entry);
  4969.  
  4970.   /* Relocate the text according to the text relocation.  */
  4971.  
  4972.   perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
  4973.               entry->text_size, reloc, entry->text_reloc_size, entry);
  4974.  
  4975.   /* Write the relocated text to the output file.  */
  4976.  
  4977.   mywrite (bytes, 1, entry->text_size, outdesc);
  4978. }
  4979.  
  4980. /* Relocate the data segment of each input file
  4981.    and write to the output file.  */
  4982.  
  4983. void
  4984. write_data ()
  4985. {
  4986.   if (trace_files)
  4987.     fprintf (stderr, "Copying and relocating data:\n\n");
  4988.  
  4989.   lseek (outdesc, output_data_offset, 0);
  4990.  
  4991.   each_full_file (copy_data, 0);
  4992.   file_close ();
  4993.  
  4994.   /* Write out the set element vectors.  See digest symbols for
  4995.      description of length of the set vector section.  */
  4996.  
  4997. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4998.   {
  4999.     int i;
  5000.     for (i = 0; i < 2 * set_symbol_count + set_vector_count; ++i) {
  5001.     fix_byte_order(&set_vectors[i], sizeof(*set_vectors));
  5002.     }
  5003.   }
  5004. #endif
  5005.  
  5006.   if (set_vector_count)
  5007.     mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  5008.          sizeof (unsigned long), outdesc);
  5009.  
  5010.   if (trace_files)
  5011.     fprintf (stderr, "\n");
  5012.  
  5013.   padfile (data_pad, outdesc);
  5014. }
  5015.  
  5016. /* Read the data segment contents of ENTRY, relocate them,
  5017.    and write the result to the output file.
  5018.    If `-r', save the data relocation for later reuse.
  5019.    See comments in `copy_text'.  */
  5020.  
  5021. void
  5022. copy_data (entry)
  5023.      struct file_entry *entry;
  5024. {
  5025.   register struct relocation_info *reloc;
  5026.   register char *bytes;
  5027.   register int desc;
  5028.  
  5029.   if (trace_files)
  5030.     prline_file_name (entry, stderr);
  5031.  
  5032.   desc = file_open (entry);
  5033.  
  5034.   bytes = (char *) alloca (entry->data_size);
  5035.  
  5036.   if (entry->datarel) reloc = entry->datarel;
  5037.   else if (output_style == OUTPUT_RELOCATABLE)    /* Will need this again */
  5038.     {
  5039.       read_file_relocation (entry);
  5040.       reloc = entry->datarel;
  5041.     }
  5042.   else
  5043.     {
  5044.       reloc = (struct relocation_info *) alloca (entry->data_reloc_size);
  5045.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  5046.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  5047.     fatal_with_file ("premature eof in data relocation of ", entry);
  5048. #ifdef MACH_O
  5049.       if (entry->file_type == IS_MACH_O)
  5050.     translate_mach_o_relocation (entry, reloc,
  5051.                      entry->data_reloc_size / sizeof (struct relocation_info));
  5052. #else
  5053. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5054.       target_to_host_reloc_byte_order(reloc,
  5055.       entry->data_reloc_size/sizeof(*reloc));
  5056. #endif
  5057. #endif
  5058.     }
  5059.  
  5060.   lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
  5061.   if (entry->data_size != read (desc, bytes, entry->data_size))
  5062.     fatal_with_file ("premature eof in data section of ", entry);
  5063.  
  5064.   perform_relocation (bytes, entry->data_start_address - entry->orig_data_address,
  5065.               entry->data_size, reloc, entry->data_reloc_size, entry);
  5066.  
  5067.   mywrite (bytes, 1, entry->data_size, outdesc);
  5068. }
  5069.  
  5070. /* Relocate ENTRY's text or data section contents.
  5071.    DATA is the address of the contents, in core.
  5072.    DATA_SIZE is the length of the contents.
  5073.    PC_RELOCATION is the difference between the address of the contents
  5074.      in the output file and its address in the input file.
  5075.    RELOC_INFO is the address of the relocation info, in core.
  5076.    RELOC_SIZE is its length in bytes.  */
  5077. /* This version is about to be severly hacked by Randy.  Hope it
  5078.    works afterwards. */
  5079.  
  5080. void
  5081. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  5082.      char *data;
  5083.      struct relocation_info *reloc_info;
  5084.      struct file_entry *entry;
  5085.      int pc_relocation;
  5086.      int data_size;
  5087.      int reloc_size;
  5088. {
  5089.   register struct relocation_info *p = reloc_info;
  5090.   struct relocation_info *end
  5091.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  5092.   int text_relocation = entry->text_start_address - entry->orig_text_address;
  5093.   int data_relocation = entry->data_start_address - entry->orig_data_address;
  5094.   int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
  5095.  
  5096.   for (; p < end; p++)
  5097.     {
  5098.       register int relocation = 0;
  5099.       register int addr = RELOC_ADDRESS(p);
  5100.       register unsigned int mask = 0;
  5101.       register unsigned int x;
  5102.  
  5103.       if (addr >= data_size)
  5104.     fatal_with_file ("relocation address out of range in ", entry);
  5105.  
  5106.       if (RELOC_EXTERN_P(p))
  5107.     {
  5108.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  5109.       symbol *sp = ((symbol *)
  5110.             (((struct nlist *)
  5111.               (((char *)entry->symbols) + symindex))
  5112.              ->n_un.n_name));
  5113.  
  5114. #ifdef N_INDR
  5115.       /* Resolve indirection */
  5116.       if ((sp->defined & ~N_EXT) == N_INDR)
  5117.         sp = (symbol *) sp->value;
  5118. #endif
  5119.  
  5120.       if (symindex >= entry->syms_size)
  5121.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5122.  
  5123.       /* If the symbol is undefined, leave it at zero.  */
  5124.       if (! sp->defined)
  5125.         relocation = 0;
  5126.       else
  5127.         relocation = sp->value;
  5128.     }
  5129. #if 1
  5130.        else if (RELOC_PCREL_P(p)) {
  5131.         /*
  5132.          * Since the symbol is not external, it must be internal.
  5133.          * Since the offset is pc-relative it has already been
  5134.          * resolved for all internal symbols.  So we just skip
  5135.          * this entry.
  5136.          */
  5137.         continue;
  5138.          }
  5139. #endif     
  5140.       else switch (RELOC_TYPE(p))
  5141.     {
  5142.     case N_TEXT:
  5143.     case N_TEXT | N_EXT:
  5144.       relocation = text_relocation;
  5145.       break;
  5146.  
  5147.     case N_DATA:
  5148.     case N_DATA | N_EXT:
  5149.       relocation = data_relocation;
  5150.       break;
  5151.  
  5152.     case N_BSS:
  5153.     case N_BSS | N_EXT:
  5154.       relocation = bss_relocation;
  5155.       break;
  5156.  
  5157.     case N_ABS:
  5158.     case N_ABS | N_EXT:
  5159.       /* Don't know why this code would occur, but apparently it does.  */
  5160.       break;
  5161.  
  5162.     default:
  5163.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  5164.     }
  5165.  
  5166.       if (RELOC_PCREL_P(p))
  5167.     relocation -= pc_relocation;
  5168.  
  5169. #ifdef RELOC_ADD_EXTRA
  5170.       relocation += RELOC_ADD_EXTRA(p);
  5171.  
  5172. #if 1      
  5173.       if (output_style == OUTPUT_RELOCATABLE)
  5174.     {
  5175.       /* If this RELOC_ADD_EXTRA is 0, it means that the
  5176.          symbol was external and the relocation does not
  5177.          need a fixup here.  */
  5178.       if (RELOC_ADD_EXTRA (p))
  5179.         {
  5180.           if (! RELOC_PCREL_P (p))
  5181.         RELOC_ADD_EXTRA (p) = relocation;
  5182.           else
  5183.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5184.         }
  5185. #if 0
  5186.       if (! RELOC_PCREL_P (p))
  5187.         {
  5188.           if ((int)p->r_type <= RELOC_32
  5189.           || RELOC_EXTERN_P (p) == 0)
  5190.         RELOC_ADD_EXTRA (p) = relocation;
  5191.         }
  5192.       else if (RELOC_EXTERN_P (p))
  5193.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5194. #endif
  5195.       continue;
  5196.     }
  5197. #endif    
  5198. #endif
  5199.  
  5200.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  5201.  
  5202.       /* Unshifted mask for relocation */
  5203.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  5204.       mask |= mask - 1;
  5205.       relocation &= mask;
  5206.  
  5207.       /* Shift everything up to where it's going to be used */
  5208.       relocation <<= RELOC_TARGET_BITPOS(p);
  5209.       mask <<= RELOC_TARGET_BITPOS(p);
  5210.  
  5211.       switch (RELOC_TARGET_SIZE(p))
  5212.     {
  5213.     case 0:
  5214.       if (RELOC_MEMORY_SUB_P(p))
  5215.         relocation -= mask & *(char *) (data + addr);
  5216.       else if (RELOC_MEMORY_ADD_P(p))
  5217.         relocation += mask & *(char *) (data + addr);
  5218.       *(char *) (data + addr) &= ~mask;
  5219.       *(char *) (data + addr) |= relocation;
  5220.       break;
  5221.  
  5222.         case 1:
  5223. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5224.       x = ((unsigned char *) (data + addr))[1]
  5225.        | (((unsigned char *) (data + addr))[0] << 8);
  5226. #endif
  5227. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5228.       x = ((unsigned char *) (data + addr))[0]
  5229.        | (((unsigned char *) (data + addr))[1] << 8);
  5230. #endif
  5231.       if (RELOC_MEMORY_SUB_P(p))
  5232.         relocation -= mask & x;
  5233.       else if (RELOC_MEMORY_ADD_P(p))
  5234.         relocation += mask & x;
  5235.       x &= ~mask;
  5236.       x |= relocation;
  5237. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5238.       ((unsigned char *) (data + addr))[1] = x;
  5239.       ((unsigned char *) (data + addr))[0] = x >> 8;
  5240. #endif
  5241. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5242.       ((unsigned char *) (data + addr))[0] = x;
  5243.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5244. #endif
  5245.       break;
  5246.  
  5247.     case 2:
  5248. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5249.       x = ((unsigned char *) (data + addr))[3]
  5250.        | (((unsigned char *) (data + addr))[2] << 8)
  5251.        | (((unsigned char *) (data + addr))[1] << 16)
  5252.        | (((unsigned char *) (data + addr))[0] << 24);
  5253. #endif
  5254. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5255.       x = ((unsigned char *) (data + addr))[0]
  5256.        | (((unsigned char *) (data + addr))[1] << 8)
  5257.        | (((unsigned char *) (data + addr))[2] << 16)
  5258.        | (((unsigned char *) (data + addr))[3] << 24);
  5259. #endif
  5260.       if (RELOC_MEMORY_SUB_P(p))
  5261.         relocation -= mask & x;
  5262.       else if (RELOC_MEMORY_ADD_P(p))
  5263.         relocation += mask & x;
  5264.       x &= ~mask;
  5265.       x |= relocation;
  5266. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5267.       ((unsigned char *) (data + addr))[3] = x;
  5268.       ((unsigned char *) (data + addr))[2] = x >> 8;
  5269.       ((unsigned char *) (data + addr))[1] = x >> 16;
  5270.       ((unsigned char *) (data + addr))[0] = x >> 24;
  5271. #endif
  5272. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5273.       ((unsigned char *) (data + addr))[0] = x;
  5274.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5275.       ((unsigned char *) (data + addr))[2] = x >> 16;
  5276.       ((unsigned char *) (data + addr))[3] = x >> 24;
  5277. #endif
  5278.       break;
  5279.  
  5280.     default:
  5281.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  5282.     }
  5283.     }
  5284. }
  5285.  
  5286. /* For OUTPUT_RELOCATABLE only: write out the relocation,
  5287.    relocating the addresses-to-be-relocated.  */
  5288.  
  5289. void coptxtrel (), copdatrel ();
  5290.  
  5291. void
  5292. write_rel ()
  5293. {
  5294.   register int i;
  5295.   register int count = 0;
  5296.  
  5297.   if (trace_files)
  5298.     fprintf (stderr, "Writing text relocation:\n\n");
  5299.  
  5300.   /* Assign each global symbol a sequence number, giving the order
  5301.      in which `write_syms' will write it.
  5302.      This is so we can store the proper symbolnum fields
  5303.      in relocation entries we write.  */
  5304.  
  5305.   for (i = 0; i < TABSIZE; i++)
  5306.     {
  5307.       symbol *sp;
  5308.       for (sp = symtab[i]; sp; sp = sp->link)
  5309.     if (sp->referenced || sp->defined)
  5310.       {
  5311.         sp->def_count = count++;
  5312. #ifndef NeXT
  5313.         /* Leave room for the reference required by N_INDR, if
  5314.            necessary.  */
  5315.         if ((sp->defined & ~N_EXT) == N_INDR)
  5316.           count++;
  5317. #endif
  5318.       }
  5319.     }
  5320.   /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
  5321.      whatever indirect blocks we have.  */
  5322. #ifndef NeXT
  5323.   if (count != defined_global_sym_count
  5324.       + undefined_global_sym_count + global_indirect_count)
  5325. #else
  5326.   if (count != defined_global_sym_count
  5327.       + undefined_global_sym_count)
  5328. #endif
  5329.     fatal ("internal error");
  5330.  
  5331.   /* Write out the relocations of all files, remembered from copy_text.  */
  5332.  
  5333.   lseek (outdesc, output_trel_offset, 0);
  5334.   each_full_file (coptxtrel, 0);
  5335.  
  5336.   if (trace_files)
  5337.     fprintf (stderr, "\nWriting data relocation:\n\n");
  5338.  
  5339.   lseek (outdesc, output_drel_offset, 0);
  5340.   each_full_file (copdatrel, 0);
  5341.  
  5342.   if (trace_files)
  5343.     fprintf (stderr, "\n");
  5344. }
  5345.  
  5346. void
  5347. coptxtrel (entry)
  5348.      struct file_entry *entry;
  5349. {
  5350.   register struct relocation_info *p, *end;
  5351.   register int reloc = entry->text_start_address - text_start;
  5352.  
  5353.   p = entry->textrel;
  5354.   end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
  5355.   while (p < end)
  5356.     {
  5357.       RELOC_ADDRESS(p) += reloc;
  5358.       if (RELOC_EXTERN_P(p))
  5359.     {
  5360.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5361.       symbol *symptr = ((symbol *)
  5362.                 (((struct nlist *)
  5363.                   (((char *)entry->symbols) + symindex))
  5364.                  ->n_un.n_name));
  5365.  
  5366.       if (symindex >= entry->syms_size)
  5367.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5368.  
  5369. #ifdef N_INDR
  5370.       /* Resolve indirection.  */
  5371.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5372.         symptr = (symbol *) symptr->value;
  5373. #endif
  5374.  
  5375.       /* If the symbol is now defined, change the external relocation
  5376.          to an internal one.  */
  5377.  
  5378.       if (symptr->defined)
  5379.         {
  5380.           RELOC_EXTERN_P(p) = 0;
  5381.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  5382. #ifdef RELOC_ADD_EXTRA
  5383.           /* If we aren't going to be adding in the value in
  5384.              memory on the next pass of the loader, then we need
  5385.          to add it in from the relocation entry.  Otherwise
  5386.              the work we did in this pass is lost.  */
  5387.           if (!RELOC_MEMORY_ADD_P(p))
  5388.         RELOC_ADD_EXTRA (p) += symptr->value;
  5389. #endif
  5390.         }
  5391.       else
  5392.         /* Debugger symbols come first, so have to start this
  5393.            after them.  */
  5394. #ifndef NeXT
  5395.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5396.                  - defined_global_sym_count
  5397.                  - undefined_global_sym_count
  5398.                  - global_indirect_count);
  5399. #else
  5400.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5401.                  - defined_global_sym_count
  5402.                  - undefined_global_sym_count);
  5403. #endif
  5404.     }
  5405.       p++;
  5406.     }
  5407.  
  5408. #ifdef MACH_O
  5409.   if (output_file_type == IS_MACH_O)
  5410.     generate_mach_o_relocations(entry->textrel,
  5411.                 entry->text_reloc_size / sizeof (struct relocation_info));
  5412. #else
  5413. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5414.     host_to_target_reloc_byte_order((struct relocation_info *) entry->textrel,
  5415.     entry->text_reloc_size/sizeof(struct relocation_info));
  5416. #endif
  5417. #endif
  5418.  
  5419.   mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
  5420. }
  5421.  
  5422. void
  5423. copdatrel (entry)
  5424.      struct file_entry *entry;
  5425. {
  5426.   register struct relocation_info *p, *end;
  5427.   /* Relocate the address of the relocation.
  5428.      Old address is relative to start of the input file's data section.
  5429.      New address is relative to start of the output file's data section.
  5430.  
  5431.      So the amount we need to relocate it by is the offset of this
  5432.      input file's data section within the output file's data section.  */
  5433.   register int reloc = entry->data_start_address - data_start;
  5434.  
  5435.   p = entry->datarel;
  5436.   end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
  5437.   while (p < end)
  5438.     {
  5439.       RELOC_ADDRESS(p) += reloc;
  5440.       if (RELOC_EXTERN_P(p))
  5441.     {
  5442.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5443.       symbol *symptr = ((symbol *)
  5444.                 (((struct nlist *)
  5445.                   (((char *)entry->symbols) + symindex))
  5446.                  ->n_un.n_name));
  5447.       int symtype;
  5448.  
  5449.       if (symindex >= entry->syms_size)
  5450.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5451.  
  5452. #ifdef N_INDR
  5453.       /* Resolve indirection.  */
  5454.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5455.         symptr = (symbol *) symptr->value;
  5456. #endif
  5457.  
  5458.       symtype = symptr->defined & ~N_EXT;
  5459.  
  5460.       if (force_common_definition
  5461.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  5462.         {
  5463.           RELOC_EXTERN_P(p) = 0;
  5464.           RELOC_SYMBOL(p) = symtype;
  5465.         }
  5466.       else
  5467.         /* Debugger symbols come first, so have to start this
  5468.            after them.  */
  5469. #ifndef NeXT
  5470.         RELOC_SYMBOL(p)
  5471.           = (((symbol *)
  5472.           (((struct nlist *)
  5473.             (((char *)entry->symbols) + symindex))
  5474.            ->n_un.n_name))
  5475.          ->def_count
  5476.          + nsyms - defined_global_sym_count
  5477.          - undefined_global_sym_count
  5478.          - global_indirect_count);
  5479. #else
  5480.         RELOC_SYMBOL(p)
  5481.           = (((symbol *)
  5482.           (((struct nlist *)
  5483.             (((char *)entry->symbols) + symindex))
  5484.            ->n_un.n_name))
  5485.          ->def_count
  5486.          + nsyms - defined_global_sym_count
  5487.          - undefined_global_sym_count);
  5488. #endif
  5489.     }
  5490.       p++;
  5491.     }
  5492. #ifdef MACH_O
  5493.   if (output_file_type == IS_MACH_O)
  5494.     generate_mach_o_relocations(entry->datarel,
  5495.                 entry->data_reloc_size / sizeof (struct relocation_info));
  5496. #else
  5497. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5498.     host_to_target_reloc_byte_order((struct relocation_info *) entry->datarel,
  5499.     entry->data_reloc_size/sizeof(struct relocation_info));
  5500. #endif
  5501. #endif
  5502.  
  5503.   mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
  5504. }
  5505.  
  5506. void write_file_syms ();
  5507. void write_string_table ();
  5508.  
  5509. /* Total size of string table strings allocated so far,
  5510.    including strings in `strtab_vector'.  */
  5511. int strtab_size;
  5512.  
  5513. /* Vector whose elements are strings to be added to the string table.  */
  5514. char **strtab_vector;
  5515.  
  5516. /* Vector whose elements are the lengths of those strings.  */
  5517. int *strtab_lens;
  5518.  
  5519. /* Index in `strtab_vector' at which the next string will be stored.  */
  5520. int strtab_index;
  5521.  
  5522. /* Add the string NAME to the output file string table.
  5523.    Record it in `strtab_vector' to be output later.
  5524.    Return the index within the string table that this string will have.  */
  5525.  
  5526. int
  5527. assign_string_table_index (name)
  5528.      char *name;
  5529. {
  5530.   register int index = strtab_size;
  5531.   register int len = strlen (name) + 1;
  5532.  
  5533.   strtab_size += len;
  5534.   strtab_vector[strtab_index] = name;
  5535.   strtab_lens[strtab_index++] = len;
  5536.  
  5537.   return index;
  5538. }
  5539.  
  5540. FILE *outstream = (FILE *) 0;
  5541.  
  5542. /* Write the contents of `strtab_vector' into the string table.
  5543.    This is done once for each file's local&debugger symbols
  5544.    and once for the global symbols.  */
  5545.  
  5546. void
  5547. write_string_table ()
  5548. {
  5549.   register int i;
  5550.  
  5551.   lseek (outdesc, output_strs_offset + output_strs_size, 0);
  5552.  
  5553.   if (!outstream)
  5554.     outstream = fdopen (outdesc, "w");
  5555.  
  5556.   for (i = 0; i < strtab_index; i++)
  5557.     {
  5558.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  5559.       output_strs_size += strtab_lens[i];
  5560.     }
  5561.  
  5562.   fflush (outstream);
  5563.  
  5564.   /* Report I/O error such as disk full.  */
  5565.   if (ferror (outstream))
  5566.     perror_name (output_filename);
  5567. }
  5568.  
  5569. /* Write the symbol table and string table of the output file.  */
  5570.  
  5571. void
  5572. write_syms ()
  5573. {
  5574.   /* Number of symbols written so far.  */
  5575.   int syms_written = 0;
  5576.   register int i;
  5577.   register symbol *sp;
  5578.  
  5579.   /* Buffer big enough for all the global symbols.  One
  5580.      extra struct for each indirect symbol to hold the extra reference
  5581.      following. */
  5582.   struct nlist *buf
  5583. #if TARGET_MACHINE==TARGET_NeXT
  5584.     = (struct nlist *) alloca ((defined_global_sym_count
  5585.                 + undefined_global_sym_count
  5586.                 + global_indirect_count)
  5587.                    * sizeof (struct nlist));
  5588. #else
  5589.     = (struct nlist *) alloca ((defined_global_sym_count
  5590.                 + undefined_global_sym_count)
  5591.                    * sizeof (struct nlist));
  5592. #endif
  5593.   /* Pointer for storing into BUF.  */
  5594.   register struct nlist *bufp = buf;
  5595.  
  5596.   /* Size of string table includes the bytes that store the size.  */
  5597.   strtab_size = sizeof strtab_size;
  5598.  
  5599.   output_syms_size = 0;
  5600.   output_strs_size = strtab_size;
  5601.  
  5602.   if (strip_symbols == STRIP_ALL)
  5603.     return;
  5604.  
  5605.   /* Write the local symbols defined by the various files.  */
  5606.  
  5607.   each_file (write_file_syms, &syms_written);
  5608.   file_close ();
  5609.  
  5610.   /* Now write out the global symbols.  */
  5611.  
  5612.   /* Allocate two vectors that record the data to generate the string
  5613.      table from the global symbols written so far.  This must include
  5614.      extra space for the references following indirect outputs. */
  5615.  
  5616.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  5617.                      + global_indirect_count) * sizeof (char *));
  5618.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  5619.                  + global_indirect_count) * sizeof (int));
  5620.   strtab_index = 0;
  5621.  
  5622.   /* Scan the symbol hash table, bucket by bucket.  */
  5623.  
  5624.   for (i = 0; i < TABSIZE; i++)
  5625.     for (sp = symtab[i]; sp; sp = sp->link)
  5626.       {
  5627.     struct nlist nl;
  5628.  
  5629. #ifdef N_SECT
  5630.     nl.n_sect = 0;
  5631. #else
  5632.     nl.n_other = 0;
  5633. #endif
  5634.     nl.n_desc = 0;
  5635.  
  5636.     /* Compute a `struct nlist' for the symbol.  */
  5637.  
  5638.     if (sp->defined || sp->referenced)
  5639.       {
  5640.         /* common condition needs to be before undefined condition */
  5641.         /* because unallocated commons are set undefined in */
  5642.         /* digest_symbols */
  5643.         if (sp->defined > 1) /* defined with known type */
  5644.           {
  5645.         /* If the target of an indirect symbol has been
  5646.            defined and we are outputting an executable,
  5647.            resolve the indirection; it's no longer needed */
  5648.         if (output_style != OUTPUT_RELOCATABLE
  5649.             && ((sp->defined & ~N_EXT) == N_INDR)
  5650.             && (((symbol *) sp->value)->defined > 1))
  5651.           {
  5652.             symbol *newsp = (symbol *) sp->value;
  5653.             nl.n_type = newsp->defined;
  5654.             nl.n_value = newsp->value;
  5655.           }
  5656.         else
  5657.           {
  5658.             nl.n_type = sp->defined;
  5659.             if (sp->defined != (N_INDR | N_EXT))
  5660.               nl.n_value = sp->value;
  5661.             else
  5662.               nl.n_value = 0;
  5663.           }
  5664.           }
  5665.         else if (sp->max_common_size) /* defined as common but not allocated. */
  5666.           {
  5667.         /* happens only with -r and not -d */
  5668.         /* write out a common definition */
  5669.         nl.n_type = N_UNDF | N_EXT;
  5670.         nl.n_value = sp->max_common_size;
  5671.           }
  5672.         else if (!sp->defined)          /* undefined -- legit only if -r */
  5673.           {
  5674.         nl.n_type = N_UNDF | N_EXT;
  5675.         nl.n_value = 0;
  5676.           }
  5677.         else
  5678.           fatal ("internal error: %s defined in mysterious way", sp->name);
  5679.  
  5680.         /* Allocate string table space for the symbol name.  */
  5681.  
  5682.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  5683.  
  5684.         /* Output to the buffer and count it.  */
  5685.  
  5686.         *bufp++ = nl;
  5687.         syms_written++;
  5688.         if (nl.n_type == (N_INDR | N_EXT))
  5689. #ifndef NeXT
  5690.           {
  5691.         struct nlist xtra_ref;
  5692.         xtra_ref.n_type == N_EXT | N_UNDF;
  5693.         xtra_ref.n_un.n_strx
  5694.           = assign_string_table_index (((symbol *) sp->value)->name);
  5695. #ifdef N_SECT
  5696.         xtra_ref.n_sect = 0;
  5697. #else
  5698.         xtra_ref.n_other = 0;
  5699. #endif
  5700.         xtra_ref.n_desc = 0;
  5701.         xtra_ref.n_value = 0;
  5702.         *bufp++ = xtra_ref;
  5703.         syms_written++;
  5704.           }
  5705. #else
  5706.         nl.n_value = assign_string_table_index (((symbol *) sp->value)->name);
  5707. #endif
  5708.       }
  5709.       }
  5710.  
  5711. #ifdef MACH_O
  5712.   if (output_file_type == IS_MACH_O)
  5713.     generate_mach_o_symbols(buf, bufp - buf);
  5714. #endif
  5715.  
  5716.   /* Output the buffer full of `struct nlist's.  */
  5717.  
  5718.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5719. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5720.   {
  5721.     int i;
  5722.  
  5723.     for (i = 0; i < bufp - buf; ++i)
  5724.       {
  5725.         fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5726.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5727.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5728.       }
  5729.   }
  5730. #endif
  5731.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5732.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5733.  
  5734.   if (syms_written != nsyms)
  5735.     fatal ("internal error: wrong number of symbols written into output file", 0);
  5736.  
  5737.   /* Now the total string table size is known, so write it into the
  5738.      first word of the string table.  */
  5739.  
  5740.   lseek (outdesc, output_strs_offset, 0);
  5741.  
  5742. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5743.   fix_byte_order(&strtab_size, sizeof(strtab_size));
  5744. #endif
  5745.  
  5746.   mywrite (&strtab_size, sizeof (int), 1, outdesc);
  5747.  
  5748.   /* Write the strings for the global symbols.  */
  5749.  
  5750.   write_string_table ();
  5751. }
  5752.  
  5753. /* Write the local and debugger symbols of file ENTRY.
  5754.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  5755.  
  5756. /* Note that we do not combine identical names of local symbols.
  5757.    dbx or gdb would be confused if we did that.  */
  5758.  
  5759. void
  5760. write_file_syms (entry, syms_written_addr)
  5761.      struct file_entry *entry;
  5762.      int *syms_written_addr;
  5763. {
  5764.   register struct nlist *p = entry->symbols;
  5765.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  5766.  
  5767.   /* Buffer to accumulate all the syms before writing them.
  5768.      It has one extra slot for the local symbol we generate here.  */
  5769.   struct nlist *buf
  5770.     = (struct nlist *) alloca (entry->syms_size + sizeof (struct nlist));
  5771.   register struct nlist *bufp = buf;
  5772.  
  5773.   /* Upper bound on number of syms to be written here.  */
  5774.   int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
  5775.  
  5776.   /* Make tables that record, for each symbol, its name and its name's length.
  5777.      The elements are filled in by `assign_string_table_index'.  */
  5778.  
  5779.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  5780.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  5781.   strtab_index = 0;
  5782.  
  5783.   /* Generate a local symbol for the start of this file's text.  */
  5784.  
  5785.   if (discard_locals != DISCARD_ALL)
  5786.     {
  5787.       struct nlist nl;
  5788.  
  5789. #if TARGET==TARGET_SEQUENT      
  5790.       nl.n_type = N_FN;
  5791. #else      
  5792.       nl.n_type = N_TEXT;
  5793. #endif
  5794.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  5795.       nl.n_value = entry->text_start_address;
  5796.       nl.n_desc = 0;
  5797. #ifdef N_SECT
  5798.       nl.n_sect = 0;
  5799. #else
  5800.       nl.n_other = 0;
  5801. #endif
  5802.       *bufp++ = nl;
  5803.       (*syms_written_addr)++;
  5804.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  5805.     }
  5806.  
  5807.   /* Read the file's string table.  */
  5808.  
  5809.   entry->strings = (char *) alloca (entry->strs_size);
  5810.   read_entry_strings (file_open (entry), entry);
  5811.  
  5812.   for (; p < end; p++)
  5813.     {
  5814.       register int type = p->n_type;
  5815.       register int write = 0;
  5816.  
  5817.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  5818.  
  5819.  
  5820.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  5821.                 /* types of symbols are never written */
  5822.                 /* globally, though they are stored */
  5823.                 /* globally.  */
  5824.         write = output_style == OUTPUT_RELOCATABLE;
  5825.       else if (!(type & (N_STAB | N_EXT)))
  5826.         /* ordinary local symbol */
  5827.     write = ((discard_locals != DISCARD_ALL)
  5828.          && !(discard_locals == DISCARD_L &&
  5829.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  5830.          && type != N_WARNING);
  5831.       else if (!(type & N_EXT))
  5832.     /* debugger symbol */
  5833.         write = (strip_symbols == STRIP_NONE);
  5834.  
  5835.       if (write)
  5836.     {
  5837.       /* If this symbol has a name,
  5838.          allocate space for it in the output string table.  */
  5839.  
  5840.       if (p->n_un.n_strx)
  5841.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  5842.                             + entry->strings);
  5843.  
  5844.       /* Output this symbol to the buffer and count it.  */
  5845.  
  5846.       *bufp++ = *p;
  5847.       (*syms_written_addr)++;
  5848.     }
  5849.     }
  5850.  
  5851. #ifdef MACH_O
  5852.   if (output_file_type == IS_MACH_O)
  5853.     generate_mach_o_symbols(buf, bufp - buf);
  5854. #else
  5855. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5856.   {
  5857.     int i;
  5858.  
  5859.     for (i = 0; i < bufp - buf; ++i)
  5860.       {
  5861.     fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5862.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5863.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5864.       }
  5865.   }
  5866. #endif
  5867. #endif
  5868.  
  5869.   /* All the symbols are now in BUF; write them.  */
  5870.  
  5871.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5872.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5873.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5874.  
  5875.   /* Write the string-table data for the symbols just written,
  5876.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  5877.  
  5878.   write_string_table ();
  5879.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  5880. }
  5881.  
  5882. /* Copy any GDB symbol segments from the input files to the output file.
  5883.    The contents of the symbol segment is copied without change
  5884.    except that we store some information into the beginning of it.  */
  5885.  
  5886. void write_file_symseg ();
  5887.  
  5888. void
  5889. write_symsegs ()
  5890. {
  5891.   lseek (outdesc, output_symseg_offset, 0);
  5892.   each_file (write_file_symseg, 0);
  5893. }
  5894.  
  5895. void
  5896. write_file_symseg (entry)
  5897.      struct file_entry *entry;
  5898. {
  5899.   char buffer[4096];
  5900.   struct symbol_root root;
  5901.   int indesc, len, total;
  5902.  
  5903.   if (entry->symseg_size == 0)
  5904.     return;
  5905.  
  5906.   output_symseg_size += entry->symseg_size;
  5907.  
  5908.   /* This entry has a symbol segment.  Read the root of the segment.  */
  5909.  
  5910.   indesc = file_open (entry);
  5911.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  5912.   if (sizeof root != read (indesc, &root, sizeof root))
  5913.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5914.  
  5915. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5916.   fix_symbol_root_byte_order(&root);
  5917. #endif
  5918.  
  5919.   /* Store some relocation info into the root.  */
  5920.  
  5921.   root.ldsymoff = entry->local_syms_offset;
  5922.   root.textrel = entry->text_start_address - entry->orig_text_address;
  5923.   root.datarel = entry->data_start_address - entry->orig_data_address;
  5924.   root.bssrel = entry->bss_start_address - entry->orig_bss_address;
  5925.   root.databeg = entry->data_start_address - root.datarel;
  5926.   root.bssbeg = entry->bss_start_address - root.bssrel;
  5927.  
  5928.   /* Write the modified root into the output file.  */
  5929.  
  5930. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5931.   fix_symbol_root_byte_order(&root);
  5932. #endif
  5933.   mywrite (&root, sizeof root, 1, outdesc);
  5934.  
  5935.   /* Copy the rest of the symbol segment unchanged.  */
  5936.  
  5937.   total = entry->symseg_size - sizeof root;
  5938.  
  5939.   while (total > 0)
  5940.     {
  5941.       len = read (indesc, buffer, min (sizeof buffer, total));
  5942.  
  5943.       if (len != min (sizeof buffer, total))
  5944.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5945.       total -= len;
  5946.       mywrite (buffer, len, 1, outdesc);
  5947.     }
  5948.  
  5949.   file_close ();
  5950. }
  5951.  
  5952. /* Define a special symbol (etext, edata, or end).  NAME is the
  5953.    name of the symbol, with a leading underscore (whether or not this
  5954.    system uses such underscores).  TYPE is its type (e.g. N_DATA | N_EXT).
  5955.    Store a symbol * for the symbol in *SYM if SYM is non-NULL.  */
  5956. static void
  5957. symbol_define (name, type, sym)
  5958.      /* const */ char *name;
  5959.      int type;
  5960.      symbol **sym;
  5961. {
  5962.   symbol *thesym;
  5963.  
  5964. #if defined(nounderscore)
  5965.   /* Skip the leading underscore.  */
  5966.   name++;
  5967. #endif
  5968.  
  5969.   thesym = getsym (name);
  5970.   if (thesym->defined)
  5971.     {
  5972.       /* The symbol is defined in some input file.  Don't mess with it.  */
  5973.       if (sym)
  5974.     *sym = 0;
  5975.     }
  5976.   else
  5977.     {
  5978.       if (thesym->referenced)
  5979.     /* The symbol was not defined, and we are defining it now.  */
  5980.     undefined_global_sym_count--;
  5981.       thesym->defined = type;
  5982.       thesym->referenced = 1;
  5983.       if (sym)
  5984.     *sym = thesym;
  5985.     }
  5986. }
  5987.  
  5988. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  5989.  
  5990. void
  5991. symtab_init ()
  5992. {
  5993.   symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
  5994.   symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
  5995.   symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
  5996.  
  5997.   /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
  5998.      (see section 4.1.2.1).  In general, it is best to use __foo and
  5999.      not worry about the confusing rules for the _foo namespace.
  6000.      But HPUX 7.0 uses _edata, so we might as weel be consistent.  */
  6001.   symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
  6002.   symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
  6003.   symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
  6004.  
  6005. #if TARGET_MACHINE==TARGET_SUN4 || TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  6006.   {
  6007.     symbol *dynamic_symbol;
  6008.     symbol_define ("__DYNAMIC", N_ABS | N_EXT, &dynamic_symbol);
  6009.     if (dynamic_symbol)
  6010.       dynamic_symbol->value = 0;
  6011.   }
  6012. #endif
  6013. #if TARGET_MACHINE==TARGET_SEQUENT
  6014.   {
  6015.     symbol *i387_flt_symbol;
  6016.     symbol_define ("_387_flt", N_ABS | N_EXT, &i387_flt_symbol);
  6017.     if (i387_flt_symbol)
  6018.       i387_flt_symbol->value = 0;
  6019.   }
  6020. #endif
  6021. #if TARGET_MACHINE==TARGET_NeXT
  6022.   {
  6023.     symbol *shlib_init_symbol;
  6024.     symbol_define ("__shared_library_initialization", N_UNDF | N_EXT, &shlib_init_symbol);
  6025.     if (shlib_init_symbol)
  6026.       shlib_init_symbol->max_common_size = sizeof (long int);
  6027.   }
  6028. #endif
  6029. }
  6030.  
  6031. /* Compute the hash code for symbol name KEY.  */
  6032.  
  6033. int
  6034. hash_string (key)
  6035.      char *key;
  6036. {
  6037.   register char *cp;
  6038.   register int k;
  6039.  
  6040.   cp = key;
  6041.   k = 0;
  6042.   while (*cp)
  6043.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  6044.  
  6045.   return k;
  6046. }
  6047.  
  6048. /* Get the symbol table entry for the global symbol named KEY.
  6049.    Create one if there is none.  */
  6050.  
  6051. symbol *
  6052. getsym (key)
  6053.      char *key;
  6054. {
  6055.   register int hashval;
  6056.   register symbol *bp;
  6057.  
  6058.   /* Determine the proper bucket.  */
  6059.  
  6060.   hashval = hash_string (key) % TABSIZE;
  6061.  
  6062.   /* Search the bucket.  */
  6063.  
  6064.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6065.     if (! strcmp (key, bp->name))
  6066.       return bp;
  6067.  
  6068.   /* Nothing was found; create a new symbol table entry.  */
  6069.  
  6070.   bp = (symbol *) xmalloc (sizeof (symbol));
  6071.   bp->refs = 0;
  6072.   bp->name = (char *) xmalloc (strlen (key) + 1);
  6073.   strcpy (bp->name, key);
  6074.   bp->defined = 0;
  6075.   bp->referenced = 0;
  6076.   bp->trace = 0;
  6077.   bp->value = 0;
  6078.   bp->max_common_size = 0;
  6079.   bp->warning = 0;
  6080.   bp->undef_refs = 0;
  6081.   bp->multiply_defined = 0;
  6082.  
  6083.   /* Add the entry to the bucket.  */
  6084.  
  6085.   bp->link = symtab[hashval];
  6086.   symtab[hashval] = bp;
  6087.  
  6088.   ++num_hash_tab_syms;
  6089.  
  6090.   return bp;
  6091. }
  6092.  
  6093. /* Like `getsym' but return 0 if the symbol is not already known.  */
  6094.  
  6095. symbol *
  6096. getsym_soft (key)
  6097.      char *key;
  6098. {
  6099.   register int hashval;
  6100.   register symbol *bp;
  6101.  
  6102.   /* Determine which bucket.  */
  6103.  
  6104.   hashval = hash_string (key) % TABSIZE;
  6105.  
  6106.   /* Search the bucket.  */
  6107.  
  6108.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6109.     if (! strcmp (key, bp->name))
  6110.       return bp;
  6111.  
  6112.   return 0;
  6113. }
  6114.  
  6115. /* Report a usage error.
  6116.    Like fatal except prints a usage summary.  */
  6117.  
  6118. void
  6119. usage (string, arg)
  6120.      char *string, *arg;
  6121. {
  6122.   if (string)
  6123.     {
  6124.       fprintf (stderr, "%s: ", progname);
  6125.       fprintf (stderr, string, arg);
  6126.       fprintf (stderr, "\n");
  6127.     }
  6128.   fprintf (stderr, "\
  6129. Usage: %s \n\
  6130.        [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  6131.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  6132.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  6133.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] [file...]\n",
  6134.        progname);
  6135.   exit (1);
  6136. }
  6137.  
  6138. /* Report a fatal error.
  6139.    STRING is a printf format string and ARG is one arg for it.  */
  6140.  
  6141. void
  6142. fatal (string, arg)
  6143.      char *string, *arg;
  6144. {
  6145.   fprintf (stderr, "%s: ", progname);
  6146.   fprintf (stderr, string, arg);
  6147.   fprintf (stderr, "\n");
  6148.   exit (1);
  6149. }
  6150.  
  6151. /* Report a fatal error.  The error message is STRING
  6152.    followed by the filename of ENTRY.  */
  6153.  
  6154. void
  6155. fatal_with_file (string, entry)
  6156.      char *string;
  6157.      struct file_entry *entry;
  6158. {
  6159.   fprintf (stderr, "%s: ", progname);
  6160.   fprintf (stderr, string);
  6161.   print_file_name (entry, stderr);
  6162.   fprintf (stderr, "\n");
  6163.   exit (1);
  6164. }
  6165.  
  6166. /* Report a fatal error using the message for the last failed system call,
  6167.    followed by the string NAME.  */
  6168.  
  6169. void
  6170. perror_name (name)
  6171.      char *name;
  6172. {
  6173.   extern int errno, sys_nerr;
  6174.   extern char *sys_errlist[];
  6175.   char *s;
  6176.  
  6177.   if (errno < sys_nerr)
  6178.     s = concat ("", sys_errlist[errno], " for %s");
  6179.   else
  6180.     s = "cannot open %s";
  6181.   fatal (s, name);
  6182. }
  6183.  
  6184. /* Report a fatal error using the message for the last failed system call,
  6185.    followed by the name of file ENTRY.  */
  6186.  
  6187. void
  6188. perror_file (entry)
  6189.      struct file_entry *entry;
  6190. {
  6191.   extern int errno, sys_nerr;
  6192.   extern char *sys_errlist[];
  6193.   char *s;
  6194.  
  6195.   if (errno < sys_nerr)
  6196.     s = concat ("", sys_errlist[errno], " for ");
  6197.   else
  6198.     s = "cannot open ";
  6199.   fatal_with_file (s, entry);
  6200. }
  6201.  
  6202. /* Report a nonfatal error.
  6203.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  6204.  
  6205. void
  6206. error (string, arg1, arg2, arg3)
  6207.      char *string, *arg1, *arg2, *arg3;
  6208. {
  6209.   fprintf (stderr, "%s: ", progname);
  6210.   fprintf (stderr, string, arg1, arg2, arg3);
  6211.   fprintf (stderr, "\n");
  6212. }
  6213.  
  6214.  
  6215. /* Output COUNT*ELTSIZE bytes of data at BUF
  6216.    to the descriptor DESC.  */
  6217.  
  6218. void
  6219. mywrite (buf, count, eltsize, desc)
  6220.      char *buf;
  6221.      int count;
  6222.      int eltsize;
  6223.      int desc;
  6224. {
  6225.   register int val;
  6226.   register int bytes = count * eltsize;
  6227.  
  6228.   while (bytes > 0)
  6229.     {
  6230.       val = write (desc, buf, bytes);
  6231.       if (val <= 0)
  6232.     perror_name (output_filename);
  6233.       buf += val;
  6234.       bytes -= val;
  6235.     }
  6236. }
  6237.  
  6238. /* Output PADDING zero-bytes to descriptor OUTDESC.
  6239.    PADDING may be negative; in that case, do nothing.  */
  6240.  
  6241. void
  6242. padfile (padding, outdesc)
  6243.      int padding;
  6244.      int outdesc;
  6245. {
  6246.   register char *buf;
  6247.   if (padding <= 0)
  6248.     return;
  6249.  
  6250.   buf = (char *) alloca (padding);
  6251.   bzero (buf, padding);
  6252.   mywrite (buf, padding, 1, outdesc);
  6253. }
  6254.  
  6255. /* Return a newly-allocated string
  6256.    whose contents concatenate the strings S1, S2, S3.  */
  6257.  
  6258. char *
  6259. concat (s1, s2, s3)
  6260.      char *s1, *s2, *s3;
  6261. {
  6262.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  6263.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  6264.  
  6265.   strcpy (result, s1);
  6266.   strcpy (result + len1, s2);
  6267.   strcpy (result + len1 + len2, s3);
  6268.   result[len1 + len2 + len3] = 0;
  6269.  
  6270.   return result;
  6271. }
  6272.  
  6273. /* Parse the string ARG using scanf format FORMAT, and return the result.
  6274.    If it does not parse, report fatal error
  6275.    generating the error message using format string ERROR and ARG as arg.  */
  6276.  
  6277. int
  6278. parse (arg, format, error)
  6279.      char *arg, *format;
  6280. {
  6281.   int x;
  6282.   if (1 != sscanf (arg, format, &x))
  6283.     fatal (error, arg);
  6284.   return x;
  6285. }
  6286.  
  6287. /* Like malloc but get fatal error if memory is exhausted.  */
  6288.  
  6289. char *
  6290. xmalloc (size)
  6291.      int size;
  6292. {
  6293.   register char *result = malloc (size);
  6294.   if (!result)
  6295.     fatal ("virtual memory exhausted", 0);
  6296.   return result;
  6297. }
  6298.  
  6299. /* Like realloc but get fatal error if memory is exhausted.  */
  6300.  
  6301. char *
  6302. xrealloc (ptr, size)
  6303.      char *ptr;
  6304.      int size;
  6305. {
  6306.   register char *result = realloc (ptr, size);
  6307.   if (!result)
  6308.     fatal ("virtual memory exhausted", 0);
  6309.   return result;
  6310. }
  6311.  
  6312. #ifdef USG
  6313.  
  6314. void
  6315. bzero (p, n)
  6316.      char *p;
  6317. {
  6318.   memset (p, 0, n);
  6319. }
  6320.  
  6321. void
  6322. bcopy (from, to, n)
  6323.      char *from, *to;
  6324. {
  6325.   memcpy (to, from, n);
  6326. }
  6327.  
  6328. getpagesize ()
  6329. {
  6330.   return (4096);
  6331. }
  6332.  
  6333. #endif
  6334.  
  6335.  
  6336. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  6337.  
  6338. static void
  6339. fix_byte_order(p, n)
  6340.     char *p;
  6341.     int n;
  6342. {
  6343.     char t;
  6344.  
  6345.     switch (n) {
  6346.  
  6347.     case 1:
  6348.     return;
  6349.  
  6350.     case 2:
  6351.     t = p[0];
  6352.     p[0] = p[1];
  6353.     p[1] = t;
  6354.     return;
  6355.  
  6356.     case 4:
  6357.     t = p[0];
  6358.     p[0] = p[3];
  6359.     p[3] = t;
  6360.     t = p[1];
  6361.     p[1] = p[2];
  6362.     p[2] = t;
  6363.     return;
  6364.  
  6365.     default:
  6366.     fatal("Internal Error in fix_byte_order, n = %d\n", 0);
  6367.     }
  6368. }
  6369.  
  6370. static void
  6371. fix_exec_header_byte_order(execP)
  6372.     struct exec *execP;
  6373. {
  6374.  
  6375. #if TARGET_MACHINE==TARGET_SUN4
  6376.     if (N_BADMAG(*execP)) {
  6377.     u_char c = * (u_char *) execP;
  6378.     execP->a_dynamic = c & 1;
  6379.     execP->a_toolversion = c >> 1;
  6380.     } else {
  6381.     u_char c = execP->a_toolversion | (execP->a_dynamic << 7);
  6382.     * (u_char *) execP = c;
  6383.     }
  6384. #elif TARGET_MACHINE!=TARGET_SEQUENT
  6385.     fix_byte_order(&execP->a_machtype, sizeof(execP->a_machtype));
  6386. #endif
  6387.     fix_byte_order(&execP->a_magic,    sizeof(execP->a_magic));
  6388.     fix_byte_order(&execP->a_text,     sizeof(execP->a_text));
  6389.     fix_byte_order(&execP->a_data,     sizeof(execP->a_data));
  6390.     fix_byte_order(&execP->a_bss,      sizeof(execP->a_bss));
  6391.     fix_byte_order(&execP->a_syms,     sizeof(execP->a_syms));
  6392.     fix_byte_order(&execP->a_entry,    sizeof(execP->a_entry));
  6393.     fix_byte_order(&execP->a_trsize,   sizeof(execP->a_trsize));
  6394.     fix_byte_order(&execP->a_drsize,   sizeof(execP->a_drsize));
  6395.     return;
  6396. }
  6397.  
  6398. static void
  6399. fix_symbol_byte_order(p, size)
  6400.     struct nlist *p;
  6401.     int size;
  6402. {
  6403.     int n;
  6404.  
  6405.     for (n = size / sizeof(*p); --n >= 0; ++p) {
  6406.     fix_byte_order(&p->n_un, sizeof(p->n_un));
  6407.     fix_byte_order(&p->n_desc, sizeof(p->n_desc));
  6408.     fix_byte_order(&p->n_value, sizeof(p->n_value));
  6409.     }
  6410.     return;
  6411. }
  6412.  
  6413. static void
  6414. target_to_host_reloc_byte_order(relocP, nrelocs)
  6415.     struct relocation_info *relocP;
  6416.     int nrelocs;
  6417. {
  6418.     u_char c[4];
  6419.  
  6420. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6421.     for (; --nrelocs >= 0; ++relocP) {
  6422.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6423.     c[0] = ((u_char *) relocP)[4];
  6424.     c[1] = ((u_char *) relocP)[5];
  6425.     c[2] = ((u_char *) relocP)[6];
  6426.     c[3] = ((u_char *) relocP)[7];
  6427.     ((u_long *) relocP)[1] = 0;
  6428. #if TARGET_MACHINE==TARGET_SUN4
  6429.     relocP->r_index = (c[0] << 16) | (c[1] << 8) | c[2];
  6430.     relocP->r_type = (enum reloc_type) (c[3] & 0x1f);
  6431.     relocP->r_extern = (c[3] & 0x80) >> 7;
  6432.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6433. #else
  6434.     relocP->r_symbolnum = (c[0] << 16) | (c[1] << 8) | c[2];
  6435.     relocP->r_pcrel = (c[3] >> 7) & 1;
  6436.     relocP->r_length = (c[3] >> 5) & 3;
  6437.     relocP->r_extern = (c[3] >> 4) & 1;
  6438. #endif
  6439.     }
  6440. #endif
  6441.     return;
  6442. }
  6443.  
  6444. static void
  6445. host_to_target_reloc_byte_order(relocP, nrelocs)
  6446.     struct relocation_info *relocP;
  6447.     int nrelocs;
  6448. {
  6449.     u_char c[4];
  6450.  
  6451. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6452.     for (; --nrelocs >= 0; ++relocP) {
  6453.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6454. #if TARGET_MACHINE==TARGET_SUN4
  6455.     c[0] = (relocP->r_index >> 16);
  6456.     c[1] = (relocP->r_index >> 8);
  6457.     c[2] = relocP->r_index;
  6458.     c[3] = (u_char) relocP->r_type | (relocP->r_extern << 7);
  6459.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6460. #else
  6461.     c[0] = (relocP->r_symbolnum >> 16);
  6462.     c[1] = (relocP->r_symbolnum >> 8);
  6463.     c[2] = relocP->r_symbolnum;
  6464.     c[3] = (relocP->r_pcrel << 7) |
  6465.         (relocP->r_length << 5) | (relocP->r_extern << 4);
  6466. #endif
  6467.     ((u_char *) relocP)[4] = c[0];
  6468.     ((u_char *) relocP)[5] = c[1];
  6469.     ((u_char *) relocP)[6] = c[2];
  6470.     ((u_char *) relocP)[7] = c[3];
  6471.     }
  6472. #endif
  6473.     return;
  6474. }
  6475.  
  6476. static void
  6477. fix_symbol_root_byte_order(p)
  6478.     struct symbol_root *p;
  6479. {
  6480.  
  6481.     fix_byte_order(&p->format, sizeof(p->format));
  6482.     fix_byte_order(&p->length, sizeof(p->length));
  6483.     fix_byte_order(&p->ldsymoff, sizeof(p->ldsymoff));
  6484.     fix_byte_order(&p->textrel, sizeof(p->textrel));
  6485.     fix_byte_order(&p->datarel, sizeof(p->datarel));
  6486.     fix_byte_order(&p->bssrel, sizeof(p->bssrel));
  6487.     fix_byte_order(&p->filename, sizeof(p->filename));
  6488.     fix_byte_order(&p->filedir, sizeof(p->filedir));
  6489.     fix_byte_order(&p->blockvector, sizeof(p->blockvector));
  6490.     fix_byte_order(&p->typevector, sizeof(p->typevector));
  6491.     fix_byte_order(&p->language, sizeof(p->language));
  6492.     fix_byte_order(&p->version, sizeof(p->version));
  6493.     fix_byte_order(&p->compilation, sizeof(p->compilation));
  6494.     fix_byte_order(&p->databeg, sizeof(p->databeg));
  6495.     fix_byte_order(&p->bssbeg, sizeof(p->bssbeg));
  6496.     fix_byte_order(&p->sourcevector, sizeof(p->sourcevector));
  6497.     return;
  6498. }
  6499.  
  6500. #endif
  6501.  
  6502. #if defined(sun) && defined(sparc)
  6503. /*
  6504.  * The pagesize on the sun4 and the sparcStation are different.
  6505.  * We want to be able to run the binary on either, so we need to
  6506.  * use the larger of the two.  This is a hack to accomplish that.
  6507.  */
  6508. int
  6509. getpagesize ()
  6510. {
  6511.   return 8192;
  6512. }
  6513. #endif
  6514.  
  6515. @
  6516.